Sub topic 10
Testing async UI with findBy and waitFor
This chapter assumes you know React function components and hooks, async/await and promises, and the basics of Jest or Vitest (test, expect, describe). It also assumes you have read the earlier chapters on render, screen, query variants, and user-event.
Why async UI needs different tests
Many components do not show their final content on the first render. They fetch data, wait for a timer, or update state after a promise resolves. A test that asserts right after render sees only the first state.
Testing Library gives you two tools for this:
findByqueries, which retry until an element appears.waitFor, which retries any callback until it stops throwing.
Both poll the DOM. By default they check about every 50 ms and give up after 1000 ms. When they give up, the test fails with the last error they saw.
A component that loads data
The examples in this chapter use a component that receives a loader function as a prop. Passing the loader in makes it easy to replace in tests.
// 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>;
}The component has two visible states. First it shows "Loading...". After the promise resolves, it shows a heading.
findBy: wait for something to appear
A findBy query is a getBy query wrapped in waitFor. It returns a promise, so you must await it. The promise resolves with the element once it exists, and rejects if it does not appear in time.
// 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();
});Each line has a reason:
getByText('Loading...')checks the initial state synchronously. It runs right afterrender, before the promise resolves, so the loading text is still there.await screen.findByRole(...)waits for the final state. The role and accessible name follow the query priority from the earlier chapter.queryByText(...)with.not.toBeInTheDocument()confirms the loading text is gone.queryByreturnsnullinstead of throwing, which is what makes this negative assertion possible.
Use the variant that matches what you expect:
| You expect | Use | Why |
|---|---|---|
| Element is there now | `getBy` | Throws immediately if missing |
| Element is absent now | `queryBy` | Returns `null` instead of throwing |
| Element will appear later | `findBy` | Retries until it appears |
| Several elements will appear later | `findAllBy` | Retries until at least one matches |
waitFor: wait for any condition
Sometimes you are not waiting for an element to appear. You may be waiting for a mock to be called, for an attribute to change, or for an element to disappear. waitFor takes a callback and runs it repeatedly until it does not throw.
// SaveButton.jsx
import { useState } from 'react';
export function SaveButton({ save }) {
const [status, setStatus] = useState('idle');
async function handleClick() {
setStatus('saving');
await save();
setStatus('saved');
}
return (
<div>
<button onClick={handleClick} disabled={status === 'saving'}>
Save
</button>
<p role="status">{status === 'saved' ? 'Saved!' : ''}</p>
</div>
);
}
// SaveButton.test.jsx
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SaveButton } from './SaveButton';
test('calls save and re-enables the button', async () => {
const user = userEvent.setup();
const save = jest.fn().mockResolvedValue();
render(<SaveButton save={save} />);
await user.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled());
expect(screen.getByRole('status')).toHaveTextContent('Saved!');
});The callback contains an assertion. If the assertion throws, waitFor tries again. When it passes, waitFor resolves.
Waiting for an element to disappear
To wait for something to go away, use waitForElementToBeRemoved. It needs the element to be present when you call it, so grab it first.
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';
import { UserGreeting } from './UserGreeting';
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();
});If the element is already gone when you call it, the function throws. For that reason, prefer findBy for the final state when you can, and use this helper when the disappearance is the event you care about.
Choosing between findBy and waitFor
findBy is the better default when you wait for one element. It reads more clearly and its error message is a normal query error.
Use waitFor when the thing you wait for is not a single element query. Examples are a mock call count, a combination of conditions, or a value read from a toHaveValue check.
// Prefer this:
expect(await screen.findByText('Saved!')).toBeInTheDocument();
// Over this:
await waitFor(() => {
expect(screen.getByText('Saved!')).toBeInTheDocument();
});Both versions behave the same. The first is shorter.
Changing timeouts
The defaults are timeout: 1000 and interval: 50. You can override them for one call:
const message = await screen.findByText('Report ready', {}, { timeout: 3000 });
await waitFor(() => expect(save).toHaveBeenCalled(), { timeout: 3000, interval: 100 });Note the argument order for findBy: the first object is the query options (such as name), and the second is the waitFor options.
You can also change the default for a whole suite with configure:
// jest.setup.js
import { configure } from '@testing-library/react';
configure({ asyncUtilTimeout: 2000 });A larger timeout does not slow passing tests, because they resolve as soon as the check passes. It only makes failing tests take longer to fail. Raise it for genuinely slow work, not to hide a test that is wrong.
Edge cases and common errors
Forgetting to await
If you forget await, the assertion runs on a pending promise. The test may pass without checking anything, or it may fail later with a confusing "not wrapped in act" warning or an error after the test has finished.
// Wrong: the promise is never awaited
expect(screen.findByText('Hello, Ada')).toBeInTheDocument();
// Right
expect(await screen.findByText('Hello, Ada')).toBeInTheDocument();Using getBy for content that arrives later
getByText('Hello, Ada') right after render throws, because the data has not arrived. Switch to findBy.
Side effects inside waitFor
waitFor may run its callback many times. Do not put actions such as user.click inside it. A click inside the callback could fire repeatedly.
// Wrong: the click may run on every retry
await waitFor(async () => {
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(save).toHaveBeenCalled();
});
// Right: act once, then wait for the result
await user.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => expect(save).toHaveBeenCalled());Several assertions in one waitFor
If a callback holds several assertions, the first failing one hides the rest, and the whole group reruns each time. Keep the callback to one assertion, or wait on the slowest condition and assert the others after it resolves.
Asserting on something that never happens
To prove that something does not appear, waitFor with a negative assertion passes on the first try, because the element is absent at once. That tells you nothing about whether it appears a moment later. If you need that guarantee, wait for a positive signal that the work finished (for example the loading text going away), then assert the element is absent.
Fake timers
If a component uses setTimeout and you use Jest fake timers, findBy and waitFor detect Jest's fake timers and advance them for you. In Vitest, make sure you pass a configuration that lets Testing Library detect fake timers, or advance them yourself with vi.advanceTimersByTime. With userEvent, pass advanceTimers to setup:
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });Without this option, user.click can hang under fake timers.
About act warnings
React warns "An update to X inside a test was not wrapped in act(...)" when state changes outside of React's tracked work. Testing Library's render, user-event, findBy, and waitFor already wrap their work in act. The warning usually means a state update happened after your test stopped waiting.
The fix is nearly always to wait for the final visible result with findBy or waitFor, not to add act by hand. If a test ends while a promise is still pending, the later state update triggers the warning.
Putting it together
A realistic async flow combines user-event, a mock, and findBy. This search box calls an injected function and lists the results:
// Search.jsx
import { useState } from 'react';
export function Search({ searchUsers }) {
const [query, setQuery] = useState('');
const [results, setResults] = useState(null);
const [error, setError] = useState(null);
async function handleSubmit(e) {
e.preventDefault();
setError(null);
try {
setResults(await searchUsers(query));
} catch {
setError('Search failed');
}
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="q">Name</label>
<input id="q" value={query} onChange={(e) => setQuery(e.target.value)} />
<button type="submit">Search</button>
{error && <p role="alert">{error}</p>}
{results && (
<ul>
{results.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
)}
</form>
);
}
// Search.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Search } from './Search';
test('lists the matching users', async () => {
const user = userEvent.setup();
const searchUsers = jest.fn().mockResolvedValue(['Ada Lovelace', 'Ada Yonath']);
render(<Search searchUsers={searchUsers} />);
await user.type(screen.getByLabelText('Name'), 'Ada');
await user.click(screen.getByRole('button', { name: 'Search' }));
expect(await screen.findAllByRole('listitem')).toHaveLength(2);
expect(searchUsers).toHaveBeenCalledWith('Ada');
});
test('shows an error when the search fails', async () => {
const user = userEvent.setup();
const searchUsers = jest.fn().mockRejectedValue(new Error('boom'));
render(<Search searchUsers={searchUsers} />);
await user.click(screen.getByRole('button', { name: 'Search' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Search failed');
});The second test shows that failure paths use the same pattern. Reject the mock, then wait for the visible error.
Summary of rules
- Use
getByfor what is there now,queryByfor what should be absent, andfindByfor what will appear. - Always
awaitfindBy,waitFor, and user-event calls. - Use
waitForfor non-element conditions, with one assertion and no side effects inside. - Wait for visible outcomes, not for arbitrary delays.
- Raise timeouts only for work that is truly slow.
Exercise
A test renders a component that loads a list from an API and then runs expect(screen.getByRole('listitem')).toBeInTheDocument() on the next line. It fails with "Unable to find an accessible element with the role listitem". The list does appear in the browser. What is wrong, and how do you fix the test?
Show answer
The data arrives after the first render, and getBy checks only once, immediately. Wait for the list with await screen.findAllByRole('listitem') (use findAllBy if there are several items, because findBy fails when more than one element matches).
Exercise
What is wrong with this code, and what should it look like? await waitFor(async () => { await user.click(screen.getByRole('button', { name: 'Save' })); expect(save).toHaveBeenCalled(); });
Show answer
waitFor reruns its callback until it stops throwing, so the click can happen several times. Perform the click once outside the callback, then wait only for the assertion: await user.click(...) followed by await waitFor(() => expect(save).toHaveBeenCalled());.
Exercise
You want to prove that a "Loading..." message disappears and a heading appears. Which queries do you use for each check, and why is queryByText used for the first?
Show answer
Use await screen.findByRole('heading', ...) to wait for the heading. Then use expect(screen.queryByText('Loading...')).not.toBeInTheDocument(). queryBy returns null when nothing matches, so the negative assertion works. getBy would throw instead.