Test a React component fetching async data on mount
Whether you can assert on asynchronous DOM updates without race conditions. Mock the API, render, then use findBy or waitFor to assert on loading and loaded states. Red flag: using getBy right after render or forgetting to await async queries.
WHAT THIS TESTS: This tests your understanding of the React Testing Library async mental model. Interviewers want to see that you know why getBy queries fail on elements that do not yet exist, and how to use the library's built-in retry mechanisms to avoid brittle tests. They also care whether you isolate the component from real network requests and whether you assert on intermediate states like loading spinners.
A GOOD ANSWER COVERS: A strong answer follows four steps in order. First, mock the API so the test is deterministic and fast, using something like MSW or jest.mock. Second, render the component and optionally assert the immediate loading state with getBy or queryBy if the loading indicator is present synchronously. Third, wait for the async data to appear using findBy queries, which combine getBy and waitFor, or use waitFor directly when asserting on mock call counts or non-element conditions. Fourth, assert the final list content and any side effects, then clean up if needed. Mention that findBy returns a Promise and must be awaited.
COMMON WRONG ANSWERS: Red flags include using getBy right after render to grab elements that will appear after the fetch, which throws because the element is not in the DOM yet. Another mistake is forgetting to await findBy or waitFor, causing the test to pass before the assertion actually runs. Some candidates suggest using setTimeout or arbitrary delays, which makes tests flaky and slow. A third anti-pattern is hitting a real API instead of mocking it, which removes determinism.
LIKELY FOLLOW-UPS: The interviewer might ask how you would test the error state, which can be done by making the mock reject and asserting on an error message with findByText. They might also ask about testing disappearance, where waitForElementToBeRemoved is useful for hiding loading spinners. Another follow-up is how to test a refetch triggered by a user action, which again uses findBy after firing an event.
ONE CONCRETE EXAMPLE: Imagine a UserList component that calls fetchUsers on mount. In the test, mock fetchUsers to return a Promise that resolves to an array of three users. Render UserList and expect screen.getByText('Loading...') to be in the document. Then write await screen.findByText('Alice') to pause the test until the resolved data renders. Optionally wrap the mock resolution in waitFor if you need to assert that fetchUsers was called exactly once. Finally assert that the list contains three list items.
Read the original → testing-library.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.