Generate Mock Service Worker Handlers for Frontend Tests
Writing MSW handlers by hand is tedious when you have dozens of API endpoints. Paste your route definitions or controller files and ask Claude to generate a complete set of Mock Service Worker handlers — including realistic response payloads and error cases.
cat src/api/routes.ts | claude -p "Generate MSW 2.x handlers for all these routes with realistic mock data and a 500 error variant for each endpoint"
Claude generates properly structured handlers:
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('/api/users/:id', ({ params }) => {
return HttpResponse.json({
id: Number(params.id),
name: 'Jane Smith',
email: 'jane@example.com',
role: 'admin',
createdAt: '2024-01-15T09:00:00Z',
});
}),
http.post('/api/users', async ({ request }) => {
const body = await request.json();
return HttpResponse.json({ id: 42, ...body }, { status: 201 });
}),
];
// Error handlers for testing failure states
export const errorHandlers = [
http.get('/api/users/:id', () => new HttpResponse(null, { status: 500 })),
];
Ask Claude to match the response shape your actual API returns — inferred from your TypeScript types or OpenAPI spec — rather than inventing arbitrary mock data. This means your tests catch real type mismatches instead of passing against unrealistic stubs.
Realistic mocks mean your tests catch the integration bugs that actually matter.
Log in to leave a comment.
The /security-review command scans your uncommitted changes for injection vectors, auth gaps, hardcoded secrets, and other common vulnerabilities.
The SessionStart hook fires when any session begins or resumes, making it ideal for loading environment variables and running one-time setup scripts.
Ask Claude to write property-based tests for your functions using fast-check — it identifies the mathematical invariants in your code and generates tests that cover inputs you'd never enumerate by hand.