我是反应测试和尝试模拟反应钩子的新手,但我在某些地方失败了。我不知道在哪里。
我有一个使用 react UseEffect 的简单反应组件。我无法使用 async jest mocks 对其进行测试。我在哪里缺乏方法?
// my Componenet.tsx
const DImage = ({
fetchImage,
style,
isDiv,
defaultImage,
...props
}: CompProps) => {
const [image, setImage] = useState<any>(defaultImage);
useEffect(() => {
fetchImage()
.then((response: any) => response.blob())
.then((data: any) => {
try {
const objectURL = URL.createObjectURL(data);
setImage(objectURL);
} catch (ex) {}
});
}, []);
if (isDiv) {
return (
<div
style={{ ...style, backgroundImage: `url('${image}')` }}
{...props}
/>
);
}
return <img src={image} style={style} {...props} />;
};
export default DImage;
// test.tsx
import React from 'react';
import DImage from './DynamicImage';
import { mount, ReactWrapper } from 'enzyme';
let dImage: ReactWrapper<any>;
describe('Button', () => {
beforeAll(() => {
fetchImage = jest.fn(async () => jest.fn(() => 'someValue'))
dImage = mount(
<DImage fetchImage={fetchImage} />
);
});
it('should be defined', () => {
expect(dImage).toBeDefined();
});
});