Testing async code
Overview
Real components do asynchronous things: fetch data, wait for debounces, show toasts that disappear after a few seconds. Tests for them must wait for the UI to update — without arbitrary sleeps — and must not depend on a real server. This lesson covers the tools for both.
Waiting for the UI
React updates asynchronously after promises resolve, so an assertion immediately after render may run too early. Use findBy… queries, which retry until the element appears (by default for up to 1 second):
test('shows courses after loading', async () => {
render(<CourseList />);
expect(screen.getByText('Loading…')).toBeInTheDocument(); // immediately
expect(await screen.findByText('React')).toBeInTheDocument(); // after the fetch
expect(screen.queryByText('Loading…')).not.toBeInTheDocument();
});For assertions that aren’t about an element appearing, use waitFor, which retries a callback until it stops throwing:
import { waitFor } from '@testing-library/react';
await waitFor(() => expect(onSave).toHaveBeenCalledWith({ title: 'React' }));
await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(3));Keep waitFor callbacks to assertions only — no clicks or other side effects inside, since they may run many times.
Never sleep
await new Promise((r) => setTimeout(r, 1000)); // ✗ slow, and still flakyFixed delays make tests slow when things are fast and flaky when the machine is busy. Always wait for a condition.
Mocking the network with MSW
You don’t want tests to call a real API: it’s slow, it changes, and you can’t easily make it fail on demand. You could mock fetch directly, but that couples tests to how you fetch (fetch vs. axios vs. TanStack Query). Mock Service Worker (MSW) intercepts requests at the network level, so your real fetching code runs unchanged:
npm install -D msw// src/mocks/handlers.js
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('/api/courses', () =>
HttpResponse.json([
{ id: 1, title: 'React' },
{ id: 2, title: 'Node.js' },
])
),
http.get('/api/courses/:id', ({ params }) =>
HttpResponse.json({ id: Number(params.id), title: 'React' })
),
http.post('/api/enrolments', async ({ request }) => {
const { courseId } = await request.json();
return HttpResponse.json({ courseId, enrolledAt: '2026-12-01' }, { status: 201 });
}),
];// src/mocks/node.js
import { setupServer } from 'msw/node';
import { handlers } from './handlers.js';
export const server = setupServer(...handlers);// vitest.setup.js
import { afterAll, afterEach, beforeAll } from 'vitest';
import { server } from './src/mocks/node.js';
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());- Default handlers cover the happy path for every test.
onUnhandledRequest: 'error'fails the test if code calls an endpoint you didn’t mock — no accidental real requests.resetHandlersremoves per-test overrides after each test.
Testing errors and edge cases
Override a handler in a single test with server.use:
import { http, HttpResponse, delay } from 'msw';
import { server } from '../mocks/node.js';
test('shows an error when loading fails', async () => {
server.use(http.get('/api/courses', () => new HttpResponse(null, { status: 500 })));
render(<CourseList />);
expect(await screen.findByRole('alert')).toHaveTextContent(/couldn’t load/i);
});
test('shows an empty state', async () => {
server.use(http.get('/api/courses', () => HttpResponse.json([])));
render(<CourseList />);
expect(await screen.findByText('No courses yet.')).toBeInTheDocument();
});
test('handles a network failure', async () => {
server.use(http.get('/api/courses', () => HttpResponse.error()));
// …
});
test('shows the loading state', async () => {
server.use(http.get('/api/courses', async () => {
await delay(100);
return HttpResponse.json([]);
}));
// …
});Bonus: the same handlers can power your app in the browser during development (setupWorker from msw/browser), so you can build UI before the backend exists.
Checking what was sent
To assert on a request body, capture it in the handler:
test('sends the course id when enrolling', async () => {
let body;
server.use(
http.post('/api/enrolments', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ ok: true }, { status: 201 });
})
);
const user = userEvent.setup();
render(<EnrolButton courseId={7} />);
await user.click(screen.getByRole('button', { name: 'Enrol' }));
await waitFor(() => expect(body).toEqual({ courseId: 7 }));
});TanStack Query in tests
Create a new QueryClient for each test (so caches don’t leak between tests) and turn off retries, or error tests will wait through three retries:
function renderWithClient(ui) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
}Fake timers
For debounces, toasts that auto-dismiss, and intervals, waiting real seconds is too slow. Fake timers let you move time forward instantly:
import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true }));
afterEach(() => vi.useRealTimers());
test('the toast disappears after 3 seconds', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<SaveButton />);
await user.click(screen.getByRole('button', { name: 'Save' }));
expect(screen.getByRole('status')).toHaveTextContent('Saved');
act(() => vi.advanceTimersByTime(3000));
expect(screen.queryByRole('status')).not.toBeInTheDocument();
});shouldAdvanceTime: truelets fake time keep ticking slowly alongside real time. Without it, user-event and Testing Library, which use timers internally, can wait forever for time that never moves — a test that just hangs until it times out.- Pass
advanceTimers: vi.advanceTimersByTimetouserEvent.setup()so user-event’s own delays between actions use the fake clock too. - Wrap time jumps in
act, so React processes the resulting state updates before you assert. - Always restore real timers in
afterEach, or a failing test leaves fake timers running for the next one.
Testing custom hooks
Most hooks are best tested through a component that uses them. For reusable hooks, renderHook renders a hook in a tiny test component:
import { act, renderHook } from '@testing-library/react';
test('useCounter increments', () => {
const { result } = renderHook(() => useCounter(5));
act(() => result.current.increment());
expect(result.current.count).toBe(6);
});result.current always holds the latest return value. State updates you trigger directly (not through user-event) must be wrapped in act.
act warnings
If you see “An update to X inside a test was not wrapped in act(…)”, an update happened after your test stopped waiting — usually a fetch resolving after the last assertion. The fix is almost always to await the final state (with findBy or waitFor) rather than adding act manually. Testing Library’s render, user-event and findBy already wrap their work in act.
A testing strategy
| Layer | Tools | What to cover |
|---|---|---|
| Pure logic | Vitest | reducers, formatting, validation schemas |
| Components | Vitest + Testing Library + MSW | most user-facing behaviour |
| End-to-end | Playwright | a few critical journeys: sign up, buy, publish |
Run the component tests on every commit in CI; they’re fast. Run end-to-end tests before deploying.
Confidence, not coverage: a project with 60% coverage of the important flows beats 100% coverage of trivial getters. Ask “what would hurt users if it broke?” and test that first.
Test a component that fetches
Write tests for CourseDetail({ id }) from *Fetching data*, which fetches /api/courses/:id. Use MSW to mock the API. Test: it shows “Loading course…” and then the course title; it shows an error message when the server returns 500 (override the handler in that test with server.use); and it shows the new course when id changes (use rerender).
import { render, screen } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, expect, test } from 'vitest';
import { CourseDetail } from './CourseDetail.jsx';
const server = setupServer(
// your handlers here
);
// your lifecycle hooks and tests hereimport { render, screen } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, expect, test } from 'vitest';
import { CourseDetail } from './CourseDetail.jsx';
const server = setupServer(
http.get('/api/courses/:id', ({ params }) =>
HttpResponse.json({ id: params.id, title: `Course ${params.id}` })
)
);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('shows loading, then the course', async () => {
render(<CourseDetail id="1" />);
expect(screen.getByText('Loading course…')).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Course 1' })).toBeInTheDocument();
});
test('shows an error when the server fails', async () => {
server.use(http.get('/api/courses/:id', () => new HttpResponse(null, { status: 500 })));
render(<CourseDetail id="1" />);
expect(await screen.findByRole('alert')).toHaveTextContent('500');
});
test('loads a new course when id changes', async () => {
const { rerender } = render(<CourseDetail id="1" />);
await screen.findByRole('heading', { name: 'Course 1' });
rerender(<CourseDetail id="2" />);
expect(await screen.findByRole('heading', { name: 'Course 2' })).toBeInTheDocument();
});Summary
- Use
findBy…queries to wait for content that appears asynchronously; usewaitForfor other async assertions. - Mock the network, not your code: MSW intercepts real
fetchcalls and returns your fake responses. - Define default handlers for the happy path and override them per test with
server.use()for errors and edge cases. - Test hooks through components or with
renderHook; wrap direct state changes inact. - Control time with
vi.useFakeTimers({ shouldAdvanceTime: true }), passadvanceTimersto user-event, and restore real timers after each test.