【问题标题】:What is the alternative the function waitForNextUpdate (@testing-library/react-hooks) in @testing-library/react for async hooks?@testing-library/react 中用于异步挂钩的函数 waitForNextUpdate (@testing-library/react-hooks) 的替代方案是什么?
【发布时间】:2023-01-13 04:14:44
【问题描述】:

我想测试我的自定义钩子,但在 React 18 中 @testing-library/react-hooks 库不起作用,我使用的是 @testing-library/react 它具有 renderHook 函数并且工作正常,但该库没有 waitForNextUpdate异步挂钩函数。出于这个原因,我无法测试我的自定义异步挂钩。

【问题讨论】:

    标签: reactjs testing react-hooks react-testing-library react-testing


    【解决方案1】:

    另一种方法是将其替换为 waitFor

    前:

    await waitForNextUpdate();
    expect(fetch).toHaveBeenCalledTimes(1)
    

    await waitFor(() => {
       expect(fetch).toHaveBeenCalledTimes(1)
    }
    
    

    【讨论】:

      【解决方案2】:

      它只在我使用actwaitFor时对我有用:

      await act(async () => {
        await waitFor(() => {
          expect(result.current.isAuthenticated).toBeUndefined();
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2022-12-29
        • 2021-10-22
        • 2019-10-26
        • 2019-10-30
        • 2020-12-01
        • 2023-03-13
        • 2021-04-10
        • 1970-01-01
        • 2021-06-02
        相关资源
        最近更新 更多