Installing and Configuring MSW for Tests
You'll learn how to install MSW and configure it to intercept HTTP requests in your test environment, giving you reliable API mocking without touching your application code.
What MSW Setup Involves
MSW (Mock Service Worker) needs two pieces: the library itself and configuration that tells your tests when to start and stop intercepting requests. Think of it like setting up a security checkpoint—you install the checkpoint infrastructure, then define when the checkpoint opens and closes for each test session.
Installation
First, install MSW as a dev dependency:
npm install --save-dev msw@latest
For Vitest with jsdom (the environment you configured earlier), you'll use MSW's Node.js request interception, not the browser service worker.
Creating Request Handlers
MSW uses "handlers" to define which requests to intercept. Create a test setup file:
// src/test/server.ts
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
export const handlers = [
http.get('/api/users', () => {
return HttpResponse.json([{ id: 1, name: 'Test User' }]);
}),
];
export const server = setupServer(...handlers);
Configuring Server Lifecycle
In your global test setup file (the one you referenced in setupFiles in vitest.config.ts):
// src/test/setup.ts
import { server } from './server';
import { beforeAll, afterEach, afterAll } from 'vitest';
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
This ensures MSW starts before tests run, resets between tests to prevent pollution, and cleans up afterward.
Key Takeaway: MSW setup requires installing the library, creating handlers with setupServer, and hooking into test lifecycle events (beforeAll, afterEach, afterAll) so every test gets a clean, predictable HTTP interception layer.