gitmyhub

msw

TypeScript ★ 18k updated 1mo ago

Industry standard API mocking for JavaScript.

A JavaScript library that intercepts outgoing API requests in the browser and Node.js and returns fake responses you define, so the same mock handlers work in unit tests, integration tests, and local development.

TypeScriptService Worker APINode.jssetup: moderatecomplexity 3/5

Mock Service Worker, usually called MSW, is a JavaScript library that lets your web app or your tests pretend an API exists when it does not — or pretend it returns different data than it really does. Instead of replacing the bits of your code that send requests, MSW sits one layer below your code and intercepts the requests themselves, then answers them with whatever fake responses you have defined.

In a web browser, MSW does this using the Service Worker API, a standard browser feature normally used for caching pages offline. The service worker catches outgoing network calls and routes them through your mock definitions; the rest of the app keeps running its real code, and you can even inspect the mocked responses in the browser's DevTools network tab as if they were real. In Node.js, where service workers do not exist, MSW uses a separate low-level interception layer that lets you reuse the exact same request handlers.

You describe the fake responses with an Express-style routing syntax (using URL patterns, parameters, wildcards, and regular expressions), then return whatever status code, headers, cookies, delay, or body you want. The same handlers work for unit tests, integration tests, end-to-end tests, and local development, so you have a single source of truth for how your network behaves across environments. This makes MSW useful when you are building a frontend against an API that does not exist yet, when you need stable test data, or when you want to debug your app without hitting a real backend. The library is written in TypeScript. The full README is longer than what was provided.

Where it fits