Back to list
yonatangross

msw-mocking

by yonatangross

The Complete AI Development Toolkit for Claude Code — 159 skills, 34 agents, 20 commands, 144 hooks. Production-ready patterns for FastAPI, React 19, LangGraph, security, and testing.

29🍴 4📅 Jan 23, 2026

SKILL.md


name: msw-mocking description: Mock Service Worker (MSW) 2.x for API mocking. Use when testing frontend components with network mocking, simulating API errors, or creating deterministic API responses in tests. context: fork agent: test-generator version: 2.0.0 tags: [msw, testing, mocking, frontend, 2026] author: OrchestKit user-invocable: false

MSW (Mock Service Worker) 2.x

Network-level API mocking for frontend tests using MSW 2.x.

Quick Reference

// Core imports
import { http, HttpResponse, graphql, ws, delay, passthrough } from 'msw';
import { setupServer } from 'msw/node';

// Basic handler
http.get('/api/users/:id', ({ params }) => {
  return HttpResponse.json({ id: params.id, name: 'User' });
});

// Error response
http.get('/api/fail', () => {
  return HttpResponse.json({ error: 'Not found' }, { status: 404 });
});

// Delay simulation
http.get('/api/slow', async () => {
  await delay(2000);
  return HttpResponse.json({ data: 'response' });
});

// Passthrough (NEW in 2.x)
http.get('/api/real', () => passthrough());

Test Setup

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

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Runtime Override

import { http, HttpResponse } from 'msw';
import { server } from '../mocks/server';

test('shows error on API failure', async () => {
  server.use(
    http.get('/api/users/:id', () => {
      return HttpResponse.json({ error: 'Not found' }, { status: 404 });
    })
  );

  render(<UserProfile id="123" />);
  expect(await screen.findByText(/not found/i)).toBeInTheDocument();
});

Anti-Patterns (FORBIDDEN)

// ❌ NEVER mock fetch directly
jest.spyOn(global, 'fetch').mockResolvedValue(...)

// ❌ NEVER mock axios module
jest.mock('axios')

// ❌ NEVER test implementation details
expect(fetch).toHaveBeenCalledWith('/api/...')

// ✅ ALWAYS use MSW
server.use(http.get('/api/...', () => HttpResponse.json({...})))

// ✅ ALWAYS test user-visible behavior
expect(await screen.findByText('Success')).toBeInTheDocument()

Key Decisions

DecisionRecommendation
Handler locationsrc/mocks/handlers.ts
Default behaviorReturn success
Override scopePer-test with server.use()
Unhandled requestsError (catch missing mocks)
GraphQLUse graphql.query/mutation
WebSocketUse ws.link() for WS mocking

Detailed Documentation

ResourceDescription
references/msw-2x-api.mdComplete MSW 2.x API reference
examples/handler-patterns.mdCRUD, auth, error, and upload examples
checklists/msw-setup-checklist.mdSetup and review checklists
scripts/handlers-template.tsStarter template for new handlers
  • unit-testing - Component isolation
  • integration-testing - Full integration tests
  • vcr-http-recording - Python equivalent

Capability Details

http-request-mocking

Keywords: http.get, http.post, http handler, REST mock Solves:

  • Mock REST API endpoints
  • Intercept HTTP requests at network level
  • Create request handlers for testing

graphql-mocking

Keywords: graphql.query, graphql.mutation, GraphQL handler, mock GraphQL Solves:

  • Mock GraphQL queries and mutations
  • Handle GraphQL variables in mocks
  • Test GraphQL error scenarios

websocket-mocking

Keywords: WebSocket, ws mock, real-time mock, socket mock Solves:

  • Mock WebSocket connections
  • Simulate real-time events
  • Test WebSocket message handling

error-simulation

Keywords: error simulation, network error, 500 error, mock error Solves:

  • Simulate API errors in tests
  • Test error handling UI
  • Mock network failures

network-delay-simulation

Keywords: delay, latency, slow response, loading state Solves:

  • Simulate slow network responses
  • Test loading state UI
  • Verify timeout handling

runtime-handler-override

Keywords: runtime override, use.once, test-specific handler, override Solves:

  • Override handlers for specific tests
  • Create one-time response handlers
  • Customize responses per test

Score

Total Score

75/100

Based on repository quality metrics

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

+10
説明文

100文字以上の説明がある

+10
人気

GitHub Stars 100以上

0/15
最近の活動

1ヶ月以内に更新

+10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

+5

Reviews

💬

Reviews coming soon