Testing async code

Topic 2 of 2 in Testing8 min readIntermediateFree course

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):

JSX
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:

JSX
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

JSX
await new Promise((r) => setTimeout(r, 1000));   // ✗ slow, and still flaky

Fixed 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:

A component calls fetch(‘/api/courses’). MSW intercepts the request at the network level and passes it to a handler, which returns HttpResponse.json with a list of courses. The component renders the data. Handlers: http.get(‘/api/courses’, () => HttpResponse.json([…])), and server.use(http.get(‘/api/courses’, () => HttpResponse.error())) as a per-test override. Your real fetch code runs unchanged.

Terminal
npm install -D msw
JavaScript
// 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 });
  }),
];
JavaScript
// src/mocks/node.js
import { setupServer } from 'msw/node';
import { handlers } from './handlers.js';

export const server = setupServer(...handlers);
JavaScript
// 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.
  • resetHandlers removes per-test overrides after each test.

Testing errors and edge cases

Override a handler in a single test with server.use:

JSX
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:

JSX
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:

JSX
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:

JSX
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: true lets 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.advanceTimersByTime to userEvent.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:

JSX
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.

Exercise

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).

JavaScript
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 here

Summary

  • Use findBy… queries to wait for content that appears asynchronously; use waitFor for other async assertions.
  • Mock the network, not your code: MSW intercepts real fetch calls 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 in act.
  • Control time with vi.useFakeTimers({ shouldAdvanceTime: true }), pass advanceTimers to user-event, and restore real timers after each test.