MSW mit Claude Code: API-Mocking für Tests und Entwicklung 2026

Mock Service Worker (MSW) fängt HTTP-Requests auf Netzwerkebene ab — kein Monkey-Patching, keine Abstraktionen. Claude Code generiert vollständige MSW-Setups für Vitest, Playwright, Jest und Storybook.

Setup: Browser und Node

SetupInstallation und Konfiguration

# Installation npm install msw --save-dev npx msw init public/ --save # Service Worker in /public // src/mocks/handlers.ts — zentrale Handler-Definition import { http, HttpResponse } from 'msw'; export const handlers = [ // GET /api/users http.get('/api/users', () => { return HttpResponse.json([ { id: '1', name: 'Alice', email: 'alice@example.com' }, { id: '2', name: 'Bob', email: 'bob@example.com' }, ]); }), // POST /api/users — Request-Body auslesen http.post('/api/users', async ({ request }) => { const body = await request.json() as CreateUserDto; return HttpResponse.json( { id: 'new-id', ...body }, { status: 201 } ); }), // Fehler simulieren http.get('/api/error', () => { return HttpResponse.json( { message: 'Internal Server Error' }, { status: 500 } ); }), ]; // src/mocks/browser.ts import { setupWorker } from 'msw/browser'; export const worker = setupWorker(...handlers); // main.tsx — nur in Development if (process.env.NODE_ENV === 'development') { const { worker } = await import('./mocks/browser'); await worker.start({ onUnhandledRequest: 'warn' }); }

Vitest + React Testing Library

NodeMSW in Unit-Tests mit Vitest

// src/mocks/server.ts — Node-Server für Tests import { setupServer } from 'msw/node'; export const server = setupServer(...handlers); // vitest.setup.ts import { server } from './src/mocks/server'; import { beforeAll, afterAll, afterEach } from 'vitest'; beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterEach(() => server.resetHandlers()); // Handler pro Test zurücksetzen afterAll(() => server.close()); // UserList.test.tsx — Test mit MSW import { render, screen, waitFor } from '@testing-library/react'; import { server } from '../mocks/server'; import { http, HttpResponse } from 'msw'; test('zeigt Fehlermeldung bei API-Fehler', async () => { // Handler für diesen Test überschreiben server.use( http.get('/api/users', () => HttpResponse.json({ message: 'Forbidden' }, { status: 403 }) ) ); render(<UserList />); await waitFor(() => { expect(screen.getByText(/Forbidden/)).toBeInTheDocument(); }); }); test('lädt und zeigt User-Liste', async () => { render(<UserList />); expect(await screen.findByText('Alice')).toBeInTheDocument(); expect(screen.getByText('Bob')).toBeInTheDocument(); });
MSW-Prompt-Tipp: "Erstelle MSW-Handler für alle API-Endpunkte in [Datei]. Erstelle auch Fehler-Szenarien für 401, 403, 500." Claude Code liest die API-Typen und generiert vollständige Handler-Sets mit realistischen Test-Daten.

GraphQL Mocking

GraphQLQueries und Mutations abfangen

// GraphQL-Handler mit MSW import { graphql, HttpResponse } from 'msw'; export const graphqlHandlers = [ graphql.query('GetUser', ({ variables }) => { return HttpResponse.json({ data: { user: { id: variables.id, name: 'Alice', email: 'alice@example.com' }, }, }); }), graphql.mutation('CreateProject', async ({ variables }) => { return HttpResponse.json({ data: { createProject: { id: 'new-project', name: variables.name }, }, }); }), // Fehler simulieren graphql.query('GetProtectedData', () => { return HttpResponse.json({ errors: [{ message: 'Unauthorized', extensions: { code: 'UNAUTHORIZED' } }], }); }), ];

Storybook Integration

StorybookStories mit realistischen API-Daten

// .storybook/preview.ts import { initialize, mswLoader } from 'msw-storybook-addon'; initialize(); export const loaders = [mswLoader]; // UserProfile.stories.tsx import type { Meta, StoryObj } from '@storybook/react'; import { http, HttpResponse } from 'msw'; const meta: Meta<typeof UserProfile> = { component: UserProfile, }; export const LoggedIn: StoryObj = { parameters: { msw: { handlers: [ http.get('/api/user/me', () => HttpResponse.json({ id: '1', name: 'Alice', plan: 'PRO' }) ), ], }, }, }; export const LoadingState: StoryObj = { parameters: { msw: { handlers: [ http.get('/api/user/me', async () => { await new Promise((r) => setTimeout(r, 9999)); // Endlos laden return HttpResponse.json({}); }), ], }, }, };

Testing-Strategien im Kurs

Im Claude Code Mastery Kurs: vollständiges MSW-Modul mit Handler-Strategien, Vitest/RTL-Integration, GraphQL Mocking und Storybook-Setup — inkl. Test-Daten-Management und CI-Konfiguration.

14 Tage kostenlos testen →