Jest.js 对测试中组件的更新未 Package 在act(...)中

7vux5j2d  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(137)
test('renders header, sidebar and data grid table', () => {
  // Axios cannot be imported in unit test
  act(() => {
    render(
      <Provider store={store}>
        <App />
      </Provider>
    );
  })
  const dataGridTableElement = screen.getByTestId('dataGridTable');
  expect(dataGridTableElement).toBeInTheDocument();
  const blockStatsElement = screen.getByTestId('blockstats');
  expect(blockStatsElement).toBeInTheDocument();
  const headerElement = screen.getByTestId('header');
  expect(headerElement).toBeInTheDocument();
  const sidebarElement = screen.getByTestId('sidebar');
  expect(sidebarElement).toBeInTheDocument();
});

这是我在那个测试文件中唯一的测试。
无论我是否将渲染放在act(...)中,都会显示相同的警告。

Warning: An update to Sidebar 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 */

这个“Sidebar”是<App />内部的一个组件。
我不知道如何解决这个问题。如果有人能帮我解决这个问题,我将不胜感激。
这是在react 18 btw中,所以Enzyme不可用。

cwtwac6a

cwtwac6a1#

基于this article,只要测试不包含任何BRAC进程并抛出此错误,则可以在测试结束时添加以下代码以从控制台中删除此错误消息:

await act(async () => {
    await new Promise(resolve => setTimeout(resolve, 0));
  });

到目前为止,没有观察到任何副作用。请留下评论或发布任何替代解决方案。

相关问题