Skip to content
jshacks.dev
Testing

Test a fetch wrapper with MSW

Test a small fetch wrapper that adds headers and throws on a bad status by answering its requests with MSW 2 handlers in Vitest.

2 min read
Summarize in AI

A wrapper that adds an auth header and checks res.ok has real logic. MSW lets the test inspect the request the wrapper actually sent.

client.test.jsJavaScript
import { test, expect, beforeAll, afterEach, afterAll } from 'vitest';
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';

async function api(path, token) {
  const res = await fetch(`https://api.example.com${path}`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

const server = setupServer(
  http.get('https://api.example.com/me', ({ request }) =>
    HttpResponse.json({ auth: request.headers.get('authorization') }),
  ),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('sends the bearer token', async () => {
  expect(await api('/me', 'abc')).toEqual({ auth: 'Bearer abc' });
});

test('throws on a bad status', async () => {
  server.use(http.get('https://api.example.com/me', () => new HttpResponse(null, { status: 401 })));
  await expect(api('/me', 'bad')).rejects.toThrow('HTTP 401');
});
Text
 ✓ client.test.js (2 tests)

 Test Files  1 passed (1)
      Tests  2 passed (2)

The resolver receives the standard Request, so headers, query parameters and the body can be echoed back for assertion. See request handler.

A handler that echoes the input proves what was sent, not what the real server accepts.

Add a test where the handler delays or returns malformed JSON, so the wrapper's parsing failure path is covered as well as the status check. Wrappers also tend to grow retries and timeouts, and each of those deserves a case.

Also inBrowser
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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.