How do you mock API calls in React tests?
Hint
MSW (Mock Service Worker) intercepts network requests at the service worker level — no mocking of fetch/axios
Full Answer
// ─── Using MSW (recommended) ──────────────────────────────────────────────────
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = setupServer(
http.get('/api/users', () => {
return HttpResponse.json([{ id: 1, name: 'Alice' }]);
}),
http.post('/api/login', async ({ request }) => {
const body = await request.json();
if (body.password === 'wrong') {
return HttpResponse.json({ message: 'Invalid password' }, { status: 401 });
}
return HttpResponse.json({ token: 'abc123' });
})
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('displays users from API', async () => {
render(<UserList />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
await screen.findByText('Alice'); // waits for async render
});
// Override for a specific test
test('shows error on failed login', async () => {
server.use(
http.post('/api/login', () => {
return HttpResponse.json({ message: 'Server error' }, { status: 500 });
})
);
render(<LoginForm />);
// ... assert error state
});
💡 MSW is the gold standard because it intercepts at the network level — your code uses the real fetch, so you test the actual data-fetching logic, not a mock of fetch. Works in both tests and browser for development.
More Testing Questions
Practice this in a timed sprint
5 free questions, no signup required