
MSW Has a Free API Mocking Library — Mock REST and GraphQL APIs Without Changing Your Application Code
Why MSW? Mock Service Worker intercepts HTTP requests at the network level. Your app code stays untouched — same fetch calls, same axios, same everything. Just add handlers. npm install msw --save-dev Define Handlers import { http , HttpResponse } from ' msw ' export const handlers = [ http . get ( ' /api/users ' , () => { return HttpResponse . json ([ { id : 1 , name : ' John ' , email : ' john@test.com ' }, { id : 2 , name : ' Jane ' , email : ' jane@test.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 HttpResponse ( null , { status : 204 }) }), ] Use in Tests (Node) import { setupServer } from ' msw/node ' import { handlers } from ' ./handlers ' const server = setupServer (... handlers ) beforeAll (() => server . listen ()) afterEach (() => server . resetHandlers ()) afterAll (() => ser
Continue reading on Dev.to JavaScript
Opens in a new tab



