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.
The component shows a loading state, then data. The test should see both, with the network answered by a fixed response.
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();
}); ✓ 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.