[英]How to test useRef with Jest and react-testing-library?
[英]Test useRef onError Fn, with React-Testing-Library and Jest
我有這個簡單的 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,以防它被調用。 我真的需要一些幫助。
您應該檢查您的函數是否被調用,這稱為測試實現細節,而您應該檢查您的 img 元素是否具有正確的 src。
即使你應該添加一些 alt 和用戶getByAltText
來選擇圖像元素
const { getByAltText } = render(<Image srcImage={undefined} fallbackImage={undefined} />);
const imageElement = getByAltText('Image Alt');
fireEvent.error(imageElement);
expect(imageElement.src).toEqual(imgToFallbackTo);
您有 2 個選擇:
將回調添加到您的道具中,該回調將在調用 whenImageIsMissing 時調用:
export interface ImageProps {
srcImage: string;
classNames?: string;
fallbackImage?: FallbackImages;
onImageMissing?:();
}
const Image = ({
srcImage,
classNames,
onImageMissing,
fallbackImage = FallbackImages.FALLBACK
}: ImageProps) => {
const imgToSourceFrom = srcImage;
const imgToFallbackTo = fallbackImage;
const imageRef = useRef(null);
const whenImageIsMissing = () => {
imageRef.current.src = imgToFallbackTo;
imageRef.current.onerror = () => {};
if (onImageMissing) onImageMissing();
};
return (
<img ref={imageRef} src={imgToSourceFrom} className={classNames} onError={whenImageIsMissing} />
);
};
然后在你的測試中插入 jest.fn 並檢查它被調用了多少次。
另一種選擇是采用 whenImageIsMissing 的實現並將其放入 image.util 文件中,然后使用 jest.spy 獲取調用次數。 由於您使用的是函數組件,因此無法直接訪問此函數。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.