When to use act() in jest unit tests with react-dom

evolon picture evolon · Feb 7, 2020 · Viewed 8.2k times · Source

According to the react unit testing documentation:

act()

To prepare a component for assertions, wrap the code rendering it and performing updates inside an act() call. This makes your test run closer to how React works in the browser.

But the test runs perfectly fine in both cases:

Without act()

it('Should return some text', () => {
  render(<TestComponent />, container);
  expect(container.textContent).toBe('some text');
});

With act()

it('Should return some text', () => {
  act(() => {
    render(<TestComponent />, container);
  });

  expect(container.textContent).toBe('some text');
})

The questions is: What exactly act() does, and when should someone use it?

Answer

slideshowp2 picture slideshowp2 · Feb 11, 2020

From the act() docs:

When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. React provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions

Further reading and examples: https://github.com/mrdulin/react-act-examples/blob/master/sync.md