
MSW Has a Free API Mocking Library — Here's How to Use It
Mocking APIs with jest.mock() or nock is fragile and tightly coupled to implementation. MSW (Mock Service Worker) intercepts actual network requests — your app doesn't know it's being mocked. What Is MSW? MSW intercepts HTTP requests at the network level using Service Workers (browser) or custom interceptors (Node.js). Your application code makes real fetch/axios calls — MSW catches them and returns your mock responses. Quick Start npm install msw --save-dev // mocks/handlers.ts import { http , HttpResponse } from ' msw ' ; export const handlers = [ http . get ( ' /api/users ' , () => { return HttpResponse . json ([ { id : 1 , name : ' John ' , email : ' john@example.com ' }, { id : 2 , name : ' Jane ' , email : ' jane@example.com ' }, ]); }), http . post ( ' /api/users ' , async ({ request }) => { const body = await request . json (); return HttpResponse . json ( { id : 3 , ... body }, { status : 201 } ); }), http . delete ( ' /api/users/:id ' , ({ params }) => { return new HttpRespon
Continue reading on Dev.to JavaScript
Opens in a new tab

