Returning Different Responses per Test
You'll learn how to override your default MSW handlers in individual tests to simulate success, error, and edge-case scenarios.
The Core Problem
Your global MSW setup defines handlers that work for most tests, but sometimes you need a specific test to receive a different response—like simulating a network failure, testing error handling, or verifying behavior when data is empty.
Using server.use() to Override
MSW's server.use() method lets you override existing handlers for just one test. It's like saying "forget the default response for this URL—use this one instead, but only for this test."
The pattern looks like this:
import { server } from './mocks/server';
import { http, HttpResponse } from 'msw';
test('displays error message when API fails', async () => {
server.use(
http.get('/api/users', () => {
return HttpResponse.json(
{ error: 'Server error' },
{ status: 500 }
)
})
);
// render and assert error UI appears
});
This override only affects this test. After the test completes, cleanup resets handlers back to their defaults.
Common Patterns
Success with different data:
server.use(
http.get('/api/users', () => {
return HttpResponse.json([/* specific test data */])
})
);
Network failure:
server.use(
http.get('/api/users', () => {
return HttpResponse.error()
})
);
Empty results:
server.use(
http.get('/api/users', () => {
return HttpResponse.json([])
})
);
Why This Matters
This approach keeps your tests isolated. Each test can verify specific scenarios without affecting others, and you don't need separate mock files for every edge case.
Key Takeaway: Use server.use() inside individual tests to override default MSW handlers for that test only, enabling you to test success, failure, and edge cases without global configuration changes.