reactjs - waitFor 不等待回调被调用

标签 reactjs jestjs react-testing-library

我这里有一个简单的测试示例,而我希望 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/

相关文章:

node.js - 在 node_modules 错误中带有 ES 模块的 Jest Typescript - 必须使用导入来加载 ES 模块 :

reactjs - react-test-renderer create()与@ testing-library/react render()

reactjs - Expect 不是 react 测试库中的函数

javascript - 如何在 React Native 中创建国家和城市下拉菜单

javascript - ElectronJS 和 React DevTools : "Extension server error: Operation failed: http://localhost:3000/has no execution context", 来源:devtools://

javascript - 使用 React 钩子(Hook)时实用函数的正确模式是什么?

reactjs - 如何将 Jest 与 opencV.js 一起使用?

reactjs - React-Testing-Library - 使用 Redux 和 Router 包装组件

reactjs - 如何使用react-testing-library为react ui Menu触发onClose?

reactjs - 当状态更新时,我们也想更新 React-Select 的 defaultValue