Skip to main content

Lesson 4 of 8

MSW - API Mocking

Mock Service Worker intercepts network requests at the Service Worker level (in browsers) or the Node.js level (in tests). This means your components make real fetch() or Axios calls - MSW handles them at the network layer, not by mocking the module. Tests are much more realistic.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

MSW Setup & Handlers

MSW Setup & Handlers
import { http, HttpResponse, delay } from 'msw';
import { setupServer } from 'msw/node';

// ---- Handler definitions ----
export const handlers = [
  // GET /api/users
  http.get('/api/users', async () => {
    await delay(100); // simulate network latency
    return HttpResponse.json([
      { id: '1', name: 'Alice Johnson', email: 'alice@example.com', role: 'admin' },
      { id: '2', name: 'Bob Smith', email: 'bob@example.com', role: 'user' },
    ]);
  }),

  // GET /api/users/:id
  http.get('/api/users/:id', async ({ params }) => {
    const { id } = params;
    if (id === 'not-found') {
      return new HttpResponse(null, { status: 404 });
    }
    return HttpResponse.json({ id, name: 'Alice Johnson', email: 'alice@example.com' });
  }),

  // POST /api/users
  http.post('/api/users', async ({ request }) => {
    const body = await request.json() as { name: string; email: string };
    // Simulate validation
    if (!body.email.includes('@')) {
      return HttpResponse.json({ error: 'Invalid email' }, { status: 422 });
    }
    return HttpResponse.json({ id: crypto.randomUUID(), ...body }, { status: 201 });
  }),

  // PATCH /api/users/:id
  http.patch('/api/users/:id', async ({ params, request }) => {
    const body = await request.json();
    return HttpResponse.json({ id: params.id, ...(body as object) });
  }),

  // DELETE /api/users/:id
  http.delete('/api/users/:id', () => {
    return new HttpResponse(null, { status: 204 });
  }),
];

// ---- Server setup (used in vitest setup.ts) ----
export const server = setupServer(...handlers);

// ---- Using MSW in tests ----
import { server } from '../mocks/server';
import { http, HttpResponse } from 'msw';
import { render, screen, waitFor } from '@/test/utils';
import { UserList } from './UserList';

describe('UserList', () => {
  it('renders users from API', async () => {
    render(<UserList />);

    // Loading state first
    expect(screen.getByText(/loading/i)).toBeInTheDocument();

    // Users appear after fetch
    expect(await screen.findByText('Alice Johnson')).toBeInTheDocument();
    expect(screen.getByText('Bob Smith')).toBeInTheDocument();
  });

  it('shows error on API failure', async () => {
    // Override handler just for this test
    server.use(
      http.get('/api/users', () => {
        return HttpResponse.json({ error: 'Server error' }, { status: 500 });
      })
    );

    render(<UserList />);
    expect(await screen.findByRole('alert')).toHaveTextContent(/failed to load/i);
    // server.resetHandlers() in afterEach restores default handler
  });

  it('shows empty state', async () => {
    server.use(http.get('/api/users', () => HttpResponse.json([])));
    render(<UserList />);
    expect(await screen.findByText(/no users found/i)).toBeInTheDocument();
  });
});

Tip

Tip

Practice MSW API Mocking in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for MSW - API Mocking

Practice Task

Note

Practice Task - (1) Write a working example of MSW API Mocking from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with MSW API Mocking is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done