This repo contains example tests to demonstrate how to test handling async UI updates in React components
- Use react testing library, which automatically wraps all renders and events in act
- You rarely if ever need to use
act
. More Info:- https://twitter.com/kentcdodds/status/1330937800321974272?lang=en
- https://kentcdodds.com/blog/fix-the-not-wrapped-in-act-warning
- https://javascript.plainenglish.io/you-probably-dont-need-act-in-your-react-tests-2a0bcd2ad65c
- https://davidwcai.medium.com/react-testing-library-and-the-not-wrapped-in-act-errors-491a5629193b
- Use react testing library async utils instead (
waitFor
,findByText
, etc.)
Watch the videos below and follow along in the code:
git clone
this reponpm install
once to setupnode_modules
- Add a
.only
to the test you want to run (test.only
) so the console isn't cluttered by other tests npm test
- Start with
promise.test
, which demonstrates testing promises in isolation - The tests are designed to be self-documenting and read through top to bottom building on concepts demonstrated in earlier tests
- Move on to
async-react.test
which demonstrates setting up assertions for UI updates in React components that happen async - Move on to
act.test
to learn more about why it's rarely necessary
- Open in VS Code and click the "run and debug" icon on the sidebar
- Open test file you want to run and click green play icon for "Jest Current File" OR run "Jest CRA Tests"
This is a good tutorial to get more comfortable with async/await syntax for working with promises: https://javascript.info/async-await
If these terms are fuzzy to you, the good news is you don't really have to understand them if you use react testing library's async utils such as waitFor
. They allow you to think about your test from a user's perspective (ie this data takes a little bit to appear after I click this button). If you're curious and would like to deepen your understanding, I have found these resources to be extremely helpful: