Skip to content
jshacks.dev
Testing

Test a React component that fetches data

Test a React 19 component that loads data in an effect by mocking the network with MSW and awaiting the result with findByText.

1 min read
Summarize in AI

The component shows a loading state, then data. The test should see both, with the network answered by a fixed response.

users.test.jsxJSX
import { test, expect, beforeAll, afterAll } from 'vitest';
import { useEffect, useState } from 'react';
import { render, screen } from '@testing-library/react';
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';

function Users() {
  const [users, setUsers] = useState(null);
  useEffect(() => {
    fetch('https://api.example.com/users')
      .then((res) => res.json())
      .then(setUsers);
  }, []);
  if (!users) return <p>Loading</p>;
  return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

const server = setupServer(
  http.get('https://api.example.com/users', () => HttpResponse.json([{ id: 1, name: 'Ada' }])),
);
beforeAll(() => server.listen());
afterAll(() => server.close());

test('shows users after loading', async () => {
  render(<Users />);
  expect(screen.getByText('Loading')).toBeTruthy();
  expect(await screen.findByText('Ada')).toBeTruthy();
});
Text
 ✓ users.test.jsx (1 test)

 Test Files  1 passed (1)
      Tests  1 passed (1)

The synchronous getByText checks the first render, and findByText waits for the list. The component never knows it is talking to a mock. See async queries.

Add a case where the handler returns a 500 to cover the error state.

Mock a slow response to confirm the loading state stays visible, and a failing one to check the error message, since the loading and error states are the ones users meet most on poor connections.

Also inFrameworks
Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.