
MSW Has a Free API That Makes API Mocking in Tests and Dev Actually Work
Mock Service Worker (MSW) intercepts network requests at the service worker level. No monkey-patching fetch. No test-specific HTTP clients. Your code doesn't know it's being mocked. Setup: Define Handlers import { http , HttpResponse } from " msw " ; export const handlers = [ // GET request http . get ( " /api/products " , () => { return HttpResponse . json ([ { id : 1 , title : " Widget " , price : 29.99 }, { id : 2 , title : " Gadget " , price : 49.99 }, ]); }), // POST with request body http . post ( " /api/products " , async ({ request }) => { const body = await request . json (); return HttpResponse . json ({ id : 3 , ... body }, { status : 201 }); }), // Dynamic params http . get ( " /api/products/:id " , ({ params }) => { return HttpResponse . json ({ id : params . id , title : " Product " }); }), // Query parameters http . get ( " /api/search " , ({ request }) => { const url = new URL ( request . url ); const query = url . searchParams . get ( " q " ); return HttpResponse . jso
Continue reading on Dev.to JavaScript
Opens in a new tab



