Using act() in Jest Unit Tests with React-Dom
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: Jest, React, Unit Test
react-dom/test-utils provides a helper, act() to make sure all the tasks like rendering, user events, and data fetching (these are considered as units of interaction with a user interface) to be processed and applied to the DOM before making an assertion.
We use act() when we are using jest with react-dom. If you are using React Testing Library, the render function is already wrapped in act(). So we don’t need to use it.
Let’s write a test to assert both async and window.open functions get called if the button component below is clicked. This is a good place to use act().
Without using act(), we cannot assert window.open to be called because the assertion happens before the async function gets executed.