Member-only story
Handling async behaviour in React component testing with Jest
I can guess why you’re here. You started testing your React components with Jest. Awesome! 😎 But then you started adding async behaviour to your components and now you started seeing these vague “fail” messages:
In today’s post, I’ll give you some recipes for common testing scenarios that deal with sync and async component update behaviour, which include:
- How to test sync updates to a component state (using act)
- How to await something that we have control over (using wait)
- How to await something that we don’t have control over (using waitFor)
We will use react-test-render to provide a lower-level understanding, but know that the test custom helpers that we’ll write often already exist in higher-level libraries such as react-testing-library.
Case 1: Test assertions on sync updates
Before we dive into async behaviour, it’s helpful to understand how sync updates work in our React testing environment.