Chapter 7 · Practice 2 of 4
Wait for async UI with findBy queries
From Testing React code
Why it matters
Actions, transitions and data fetching update the screen after a delay, so asserting immediately makes tests flaky.
- Use
findByqueries, which retry until the element appears or a timeout passes. - Use
waitForfor other assertions. - Avoid fixed
setTimeoutsleeps: they stay flaky and slow.
Mock network calls at the boundary, for example with Mock Service Worker, rather than mocking your own hooks or the component under test. That way the test still covers your loading and error states, and you can test what happens when the server returns an error.
Avoid
- Fixed
setTimeoutsleeps in tests - Mocking the component under test