reactjs - 如何在图像元素加载事件后测试状态变化?
问题描述
我有以下代码:
return (
<img
ref={imgRef}
src={url}
alt={alt}
onLoad={() => {
if (imgRef.current?.naturalWidth) setIsImgLoaded(true);
}}
style={!isImgLoaded ? { display: 'none' } : {}}
/>
因此,当图像完成加载(通过检查其naturalWidth
)时,我更新isImgLoaded
totrue
并显示它(一开始,如您所见,我已display: none
为图像设置)。
在我的测试中,每当我尝试这样做时:
expect(screen.getByRole('img')).toExist()
我得到一个错误TestingLibraryElementError: Unable to find role="img"
,即使我尝试使用waitFor
or findByRole
。
我能做些什么?
解决方案
您需要显式触发图像的onLoad
事件以触发其回调并使图像在测试期间可见。
test("image is visible after loading", () => {
render(<TestComponent />)
// Use `{ hidden: true }` to access the image while it's not visible
const image = screen.getByRole('img', { hidden: true })
fireEvent.load(image)
// No longer requires `{ hidden: true }` as the image is now visible
expect(screen.getByRole('img')).toBeInTheDocument()
});