Mock an API error with MSW
Simulate a 500 response or a network failure for one test with server.use, HttpResponse and an HttpResponse.error call in MSW 2.
The happy path is easy. The error path is where the bugs are, and MSW lets one test override the default handler.
import { test, expect, beforeAll, afterEach, afterAll } from 'vitest';
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
const server = setupServer();
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('server error', async () => {
server.use(
http.get('https://api.example.com/items', () =>
HttpResponse.json({ message: 'boom' }, { status: 500 }),
),
);
const res = await fetch('https://api.example.com/items');
expect(res.status).toBe(500);
});
test('network failure', async () => {
server.use(http.get('https://api.example.com/items', () => HttpResponse.error()));
await expect(fetch('https://api.example.com/items')).rejects.toThrow(TypeError);
}); ✓ errors.test.js (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)server.use prepends a handler for the current test, and resetHandlers in afterEach removes it. HttpResponse.error() makes fetch reject with a TypeError, as a dropped connection does. See network behavior.
Keep the mock faithful to what the real API returns, including its error body, or the test only proves your assumption.
Test the retry or error banner your UI shows for each status you handle, such as 404 and 503, since each one often takes a separate branch.