我正在创建一个延迟加载图像加载器组件,如果图像可见时间超过 500 毫秒,它将加载图像。
它按预期工作,但我无法编写测试来验证它
我尝试过 jest.runallTimers、setTimeout 但没有成功。我在谷歌上搜索了如何在 useEffect 钩子中使用 settimeout 测试代码,但没有一个对我有用。
我正在分享一个代码和框链接,以防有人有兴趣提供帮助。
https://codesandbox.io/s/optimistic-aryabhata-1dtru?file=/__tests__/index.test.js
答案 0 :(得分:1)
试试玩笑的done()
:
it('your async test case', (done) => {
setTimeout(() => {
// your expect statement
done();
}, 1000);
});
答案 1 :(得分:1)
要测试一段时间后呈现的图像,您可以这样做:
it("shows Loading and then renders the image", async (done) => {
render(<LazyloadImage />);
expect(await screen.findByTestId("fallbackText")).toBeInTheDocument();
expect(
await screen.findByTestId("image", {}, { timeout: 500 })
).toBeInTheDocument();
done();
});
你的自定义钩子有问题(导致测试失败),所以我从组件中删除了它,但在 500 毫秒后留下了其他所有东西来渲染图像。
这是一个有效的 sandbox