Skip to content
jshacks.dev
Testing

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.

1 min read
Summarize in AI

The happy path is easy. The error path is where the bugs are, and MSW lets one test override the default handler.

errors.test.jsJavaScript
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);
});
Text
 ✓ 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.

Also inAPIs
Taggedmsw
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.