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.
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.
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');
}); ✓ 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.