Jest.js React测试库:你能模仿吗< img>?

5uzkadbs  于 9个月前  发布在  Jest
关注(0)|答案(1)|浏览(130)

使用React,我有一个覆盖组件,它在<img>的顶部渲染,使用各种回调和其他技巧将其宽度/高度/左/顶部设置为图像的宽度/高度。当我渲染组件时,onload不会触发。当我通过react测试库手动运行fireEvent.load(img)时,它会正确触发,但没有设置图像的任何属性(clientWidth,actualWidth,etc.).我需要这些,因为如果width/height为零,Overlay不会渲染。我相信这些没有设置,因为react测试库实际上并不计算组件的布局/渲染。
我想我会模拟<img>标签,但似乎你不能这样做。我试图模拟global.Image,但它的构造函数似乎没有被渲染器调用。
有办法模拟<img>或手动设置clientWidthactualWidth等吗?
基本上,我的代码看起来像这样:

...
const [imgLoaded, setImageLoaded] = useState(false);
const onLoad = ()=>setImageLoaded(true);
const [imgWidth, setImageWidth] = useState();
useEffect(()=>{
   if (!imgLoaded){
      return;
   }
   //imgRef assigned elsewhere
   setImageWidth(imgRef.actualWidth);
}, [imgLoaded]);
......
return <>
   <img onload={onLoad}/>
   <Overlay width={imgWidth}/>

字符串

n9vozmp4

n9vozmp41#

对于mock <img>标记,您可以使用 Object.defineProperty() 方法手动设置clientWidthactualWidth等属性,以在imgRef对象上定义这些属性。我将创建一个实用函数来mock这些属性。类似于:

function mockImageProperties(image, properties) {
  for (const [key, value] of Object.entries(properties)) {
    Object.defineProperty(image, key, {
      value,
      writable: true, // You can use them as per your requirement.
      configurable: true,
    });
  }
};

字符串
然后在测试文件中:

// ...Rest of the code
it('should test', () => {
  const { getByRole } = render(<YourComponent />);

  const image = getByRole('img');
  mockImageProperties(image, {
    clientWidth: 100,
    actualWidth: 100,
    // Mock other props as needed
  });

  fireEvent.load(image);

  // Your test assertions
});

相关问题