patterntypescriptModerate
API Mocking for Frontend Development: Contract-based mocks that match the real API
Viewed 0 times
mswmock-service-workerapi-mockingfrontendcontract-testingopenapi
browsernodejs
Problem
Frontend teams blocked on backend development resort to hardcoded fake data or inconsistent ad-hoc mocks. When the real API ships, integration reveals mismatches between the mock contract and actual behavior.
Solution
Use MSW (Mock Service Worker) to intercept requests at the network level in the browser and in Node test environments. Define mock handlers based on the agreed OpenAPI spec. Share mock handlers between browser development and unit/integration tests.
Why
MSW intercepts at the fetch/XHR layer, making mocks transparent to application code. Defining handlers from the OpenAPI spec keeps mocks in sync with the contract. Shared handlers between dev and test reduce divergence.
Gotchas
- MSW requires a service worker registration for browser use — ensure the sw.js file is served from the root.
- MSW does not validate requests against the spec automatically — combine with a validator for strict contract testing.
- Mock handlers that are too permissive (returning happy-path data always) hide integration bugs — add realistic error scenarios.
Code Snippets
MSW handler for a user endpoint
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/api/users/:id', ({ params }) => {
if (params.id === 'not-found') {
return HttpResponse.json({ code: 'NOT_FOUND' }, { status: 404 })
}
return HttpResponse.json({
id: params.id,
name: 'Alice',
email: 'alice@example.com'
})
})
]
// browser/main.ts
import { setupWorker } from 'msw/browser'
import { handlers } from './mocks/handlers'
if (import.meta.env.DEV) {
const worker = setupWorker(...handlers)
await worker.start()
}Revisions (0)
No revisions yet.