Simulating Network Errors and Timeouts
You'll learn how to test loading states and error boundaries by making MSW handlers fail or delay responses.
When testing real-world applications, you need to verify how your components handle network failures and slow connections. MSW makes this straightforward: instead of returning normal data, your handlers can return errors or introduce artificial delays.
The Core Idea
MSW's HttpResponse provides two special methods for simulating problems:
HttpResponse.error()— simulates a complete network failure (like lost connection)delay(ms)— pauses before sending the response, testing loading states
You can use these in test-specific handlers to override your normal successful responses.
Testing Network Errors
import { http, HttpResponse, delay } from 'msw';
test('shows error when API fails', async () => {
server.use(
http.get('/api/users', () => {
return HttpResponse.error();
})
);
render(<UserList />);
const errorMessage = await screen.findByText(/failed to load/i);
expect(errorMessage).toBeInTheDocument();
});
Testing Slow Networks
test('shows loading spinner during fetch', async () => {
server.use(
http.get('/api/users', async () => {
await delay(200); // Simulate 200ms latency
return HttpResponse.json({ users: [] });
})
);
render(<UserList />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
await waitFor(() => {
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});
});
Think of this like a flight simulator: you're creating controlled "emergencies" to verify your UI handles them gracefully without actually breaking real networks.
Key Takeaway: Use HttpResponse.error() to test failure handling and delay() to test loading states—MSW lets you simulate unreliable networks in a controlled, repeatable way.