【发布时间】:2020-05-14 17:17:47
【问题描述】:
我有这个简单的 fallbackImage 组件:
export interface ImageProps {
srcImage: string;
classNames?: string;
fallbackImage?: FallbackImages;
}
const Image = ({
srcImage,
classNames,
fallbackImage = FallbackImages.FALLBACK
}: ImageProps) => {
const imgToSourceFrom = srcImage;
const imgToFallbackTo = fallbackImage;
const imageRef = useRef(null);
const whenImageIsMissing = () => {
imageRef.current.src = imgToFallbackTo;
imageRef.current.onerror = () => {};
};
return (
<img ref={imageRef} src={imgToSourceFrom} className={classNames} onError={whenImageIsMissing} />
);
};
export default Image;
完美运行。我使用Jest 和React-Testing-Library 对其进行了测试。除了一种情况外,我已经测试了所有情况。这个:
const whenImageIsMissing = () => {
imageRef.current.src = imgToFallbackTo;
imageRef.current.onerror = () => {}; // This line.
};
这条线基本上可以防止两个图像都丢失的无限循环
问题:
我想测试我的onerror 函数是否被调用了一次。我真的很想怎么做。这是测试...
const { container } = render(<Image srcImage={undefined} fallbackImage={undefined} />);
const assertion = container.querySelector('img').onerror;
fireEvent.error(container.firstElementChild);
console.log(container.firstElementChild);
expect(container.firstElementChild.ref.current.onerror).toHaveBeenCalledTimes(1);
// This though has no reference to a real value. Is an example of what I want to get at.
问题: 如何访问 ref 回调函数并查看我的函数被调用了多少次?
对此有任何想法。我不知所措,我尝试嘲笑refs,我尝试嘲笑和监视组件。我尝试使用 act 和 async/await,以防它被调用。我真的需要一些帮助..
【问题讨论】:
标签: reactjs typescript unit-testing react-hooks react-testing-library