Real applications don't update instantly. When testing components that:
useDebounce)setTimeoutA synchronous test checking screen.getByText(...) immediately after an action will fail because the data hasn't arrived in the DOM yet!
findBy for Asynchronous DOM ElementsTo test components with asynchronous data, swap getBy... for findBy....
findBy returns a Promise that polls the DOM repeatedly (using waitFor under the hood) until the element appears or a timeout occurs:
waitForWhen you need to wait for a complex condition (e.g. verifying that a mock function was called after a debounce delay), use waitFor():
getByText and findByText in React Testing Library?await new Promise(r => setTimeout(r, 1000))) in unit tests?vi.fn() on global.fetch?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Writing Unit Tests for Functional Components | Diagnosing Memory Leaks and Detached DOM Nodes |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.