我这里有一个简单的测试示例,而我希望 waitAFor 等待调用 fetch 方法,但测试在 3 秒后结束。它不会等待 7 秒。
const TestComponent = () => {
setTimeout(() => {
fetch();
}, 6000);
return <div>Hello</div>;
};
jest.mock("./service");
describe("Test", () => {
let container = null;
beforeEach(() => {
container = render(<TestComponent />);
});
test("should fetch", async () => {
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
});
});
最佳答案
此类操作不应等待未指定的时间,这可能会导致进程挂起。
文档指出 waitFor
超时失败:
The default timeout is 1000ms which will keep you under Jest's default timeout of 5000ms.
如果预计会有延迟,则可以显式指定超时值:
test("should fetch", async () => {
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1), { timeout: 8000 });
}, 10000);
由于像 HTTP 请求这样的长异步操作在测试中并不常见,因此实时等待它们是不切实际的,这就是 Jest fake Timer API 的用途。
关于reactjs - waitFor 不等待回调被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64293129/