【发布时间】:2021-09-10 13:25:50
【问题描述】:
我有一个单元测试,其中包括渲染一个使用useSWR 获取数据的组件。但是在调用 expect() 之前数据还没有准备好,因此测试失败。
test("StyleOptionDetails contains correct style option number", () => {
renderWithMockSwr(
<StyleOptionDetails
{...mockIStyleOptionDetailsProps}
/>
)
expect(screen.getByText(123)).toBeInTheDocument();
});
但如果我延迟setTimeout(),它将通过测试。
setTimeout(() => {
console.log('This will run after 2 second')
expect(screen.getByText(123)).toBeInTheDocument();
}, 2000);
产生延迟或等待数据的正确方法是什么?
【问题讨论】:
-
嘿,我的这个答案可能会对你有所帮助,Web Fetch API (waiting the fetch to complete and then executed the next instruction)。祝你好运。
-
使用 findBy 或 waitFor testing-library.com/docs/dom-testing-library/api-async
-
您还可以将测试用例设为“异步”,并在异步语句之前使用“等待”。
-
在测试期间很可能没有达到预期 - 测试通过并没有告诉您任何有用的信息。阅读jestjs.io/docs/asynchronous。
-
谢谢大家的意见!进行测试
async并使用await findBy而不是getBy完成了这项工作。如果您想回答这个问题,那么我会将其标记为答案 - 我猜谁是第一个 @HoldOffHunger @WebbH @edison16029
标签: reactjs unit-testing jestjs react-testing-library swr