Search code examples
reactjsjestjsreact-testing-library

An update to Component inside a test was not wrapped in act(...)


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();
});

This is the only test I have in that test file.

No matter if I put the render inside an act(...) or not, the same warning would be shown.

    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 */

That "Sidebar" is a component inside <App />.

I have no idea how to solve this issue. It would be much appreciate if anyone can help me out with this.

This is in react 18 btw, so Enzyme is not usable.


Solution

  • Based on this article, as long as the test does not contain any async process and have this error thrown, it is safe to add the following code at the end of the test to remove this error message from the console:

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

    No side effects have been observed so far. Please leave comments or post any alternative solutions for this issue.