Part 48: Mocking Network APIs with MSW (Mock Service Worker)

Part 48 Technology Updated September 12, 2026

Part 48: Mocking Network APIs with MSW (Mock Service Worker)

Mocking fetch manually with vi.spyOn(window, 'fetch') creates fragile tests that break whenever API endpoints or headers change. Mock Service Worker (MSW) intercepts HTTP requests at the network layer.


1. Setting Up MSW Handlers

npm install -D msw

src/mocks/handlers.js:

import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('https://api.devifyblog.com/articles', () => {
    return HttpResponse.json([
      { id: 1, title: 'Mastering React 19' },
      { id: 2, title: 'Fullstack Next.js Guide' }
    ]);
  }),

  http.post('https://api.devifyblog.com/login', async ({ request }) => {
    const body = await request.json();
    if (body.email === 'admin@devify.com') {
      return HttpResponse.json({ token: 'mock-jwt-token', user: { name: 'Admin' } });
    }
    return new HttpResponse(null, { status: 401 });
  })
];

2. Server Setup for Vitest

src/mocks/server.js:

import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);

Vitest Setup File:

import { beforeAll, afterEach, afterAll } from 'vitest';
import { server } from './mocks/server';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Key Takeaways

  • MSW intercepts network traffic seamlessly in Node (for tests) and the browser (for development).
  • Decouples tests from backend availability while testing genuine async HTTP behavior.

In Part 49, we will explore React Security Best Practices: XSS, CSRF & Token Storage!