React Best Practices

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 findBy queries, which retry until the element appears or a timeout passes.
  • Use waitFor for other assertions.
  • Avoid fixed setTimeout sleeps: 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 setTimeout sleeps in tests
  • Mocking the component under test