Sub topic 10
Testing async UI with findBy and waitFor
This chapter assumes you can write basic React Testing Library tests, know the getBy and queryBy variants, and are comfortable with promises and async/await. Many components show a loading state first and the real content later. The test has to wait for that change without guessing how long it takes.
Why async UI needs special handling
A getBy query runs once, immediately. If the element has not appeared yet, it throws. Components that fetch data in useEffect render their final content only after a promise resolves, so a plain getBy for that content fails.
Testing Library offers two tools for this:
findByqueries return a promise. They retry until the element appears or a timeout passes. The default timeout is 1000 ms.waitForretries a callback until it stops throwing.
Both poll the DOM at short intervals, and both are already wrapped in act for you.
Waiting for an element with findBy
A findBy query is getBy plus waiting. Always await it.
// UserGreeting.jsx
import { useEffect, useState } from 'react';
export function UserGreeting({ loadUser }) {
const [user, setUser] = useState(null);
useEffect(() => {
loadUser().then(setUser);
}, [loadUser]);
if (!user) return <p>Loading...</p>;
return <h1>Hello, {user.name}</h1>;
}
// UserGreeting.test.jsx
import { render, screen } from '@testing-library/react';
import { UserGreeting } from './UserGreeting';
test('shows a loading state, then the user name', async () => {
const loadUser = jest.fn().mockResolvedValue({ name: 'Ada' });
render(<UserGreeting loadUser={loadUser} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
});The test uses each variant for a different job:
getByTextasserts the loading state, which is present right afterrender.findByRolewaits for the heading that appears after the promise resolves.queryByTextreturnsnullinstead of throwing, so it can assert that the loading text is gone.
Waiting for a condition with waitFor
Use waitFor when you are not waiting for an element to appear. A typical case is an assertion on a mock, or a check that something disappears.
import { render, screen, waitFor } from '@testing-library/react';
import { UserGreeting } from './UserGreeting';
test('calls loadUser once on mount', async () => {
const loadUser = jest.fn().mockResolvedValue({ name: 'Ada' });
render(<UserGreeting loadUser={loadUser} />);
await waitFor(() => expect(loadUser).toHaveBeenCalledTimes(1));
expect(await screen.findByText('Hello, Ada')).toBeInTheDocument();
});For an element that must disappear, use waitForElementToBeRemoved. It needs the element to be present when you call it.
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';
test('removes the loading text', async () => {
const loadUser = jest.fn().mockResolvedValue({ name: 'Ada' });
render(<UserGreeting loadUser={loadUser} />);
await waitForElementToBeRemoved(() => screen.queryByText('Loading...'));
expect(screen.getByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
});Choosing between them
| Situation | Use |
|---|---|
| Element will appear later | `findBy` |
| Element will disappear | `waitForElementToBeRemoved` |
| Non-DOM condition, such as a mock call | `waitFor` |
| Element is already there | `getBy` |
Prefer findBy whenever it fits. It gives a clearer error message than waitFor and keeps the test shorter.
Common mistakes
- Forgetting
await. Without it, the test finishes before the query resolves. It may pass without checking anything, or fail with a warning later. - Using
waitForwithgetByfor a single element.await screen.findBy...does the same job more clearly. - Wrapping
findByinwaitFor. It already waits. - Raising the timeout to hide a bug. If the default 1000 ms is not enough, pass
{ timeout: 3000 }only when the delay is real. Otherwise the mock or the component is likely wrong. - Asserting absence with
findBy.findBywaits for presence. To check that something never appears, usequeryByafter the UI has settled.
Exercise
A test clicks "Save" and must confirm that the text "Saved!" appears after an async request. Which query do you use, and why not getByText?
Show answer
Use await screen.findByText('Saved!'). getByText runs once and throws if the text has not rendered yet. findByText retries until the text appears or the timeout passes.
Exercise
What is wrong with this code? await waitFor(() => { user.click(button); expect(onSave).toHaveBeenCalled(); });
Show answer
waitFor re-runs the callback until it passes, so the click can fire more than once. Click outside the callback, then wait only on the assertion: await user.click(button); await waitFor(() => expect(onSave).toHaveBeenCalled());.