【问题标题】:My tests are passing, but I always have this warning我的测试通过了,但我总是有这个警告
【发布时间】:2021-12-31 00:18:37
【问题描述】:

我正在使用 React-Testing-Library,到目前为止我的测试都通过了,但我有一个警告,我无法理解或不知道如何解决。

警告是……

console.error
      Warning: An update to App inside a test was not wrapped in act(...).
      
      When testing, code that causes React state updates should be wrapped into act(...):
      
      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */
      
      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
          at App

在我的 App.js 中出现错误。

 let newData = await random();
      27 |     setData(newData[0]);
    > 28 |     setLoading(false);
         |     ^
      29 |   };
      30 |   useEffect(() => {
      31 |     getter();

这是我的 App.test 文件。

describe("async call to render Home component", () => {
  test("happy, with data - testing the async call", async () => {
    fetch.mockResponseOnce(JSON.stringify([{ test: "data" }]));
    render(<App />)
    const element = await screen.findByTestId('homeComponent')
    expect(element).toBeInTheDocument()
  })
  test("sad, no data - testing the async call",  async () => {
    fetch.mockResponseOnce(JSON.stringify({}))
    render(<App />)
    const element = await screen.getByText(/loading.../i)
    expect(element).toBeInTheDocument()
  })
})

我不确定这是否只是使用异步功能进行测试的过程。但是还是有点不确定,如果以后警告可能是个问题,我宁愿现在解决。

任何帮助将不胜感激。

【问题讨论】:

  • 请提供被测组件的完整代码。

标签: reactjs unit-testing testing jestjs react-testing-library


【解决方案1】:

每次使用 render(&lt;App /&gt;) 渲染组件时,都会使用 setLoading(false) 函数调用更新组件的状态。

React-Testing-Library 警告您仅在包装在 act(...) 中时才运行状态更改函数。

要删除警告,请将您的测试更改为使用此:

act(() => {
    render(<App />)
});

PS:请尝试更仔细地阅读您的错误消息。该警告会将您链接到 the react documentation on act,它准确地解释了如何解决您的问题。

【讨论】:

  • 不幸的是,我确实尝试过,但仍然出现警告
  • 您能发布您的测试和应用文件的完整源代码吗? @fluffy-lionz
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 2020-10-11
  • 2013-11-18
  • 2023-04-04
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多