MSW (Mock Service Worker) is a client-side API mocking library that uses Service Workers.
Server-less. Doesn't establish any servers, operates entirely in a browser;
Deviation-free. Intercepts outgoing requests from a page and mocks their responses;
Mocking as a tool. Enable/change/disable the mocking logic on runtime instantly without any compilations or rebuilds. Control the MSW lifecycle from your browser's DevTools.
Essentials. Mock status codes, headers, response delays, and create custom request handlers and response resolvers.
Familiar. MSW supports express-like request path definitions, enabling:
You can start with MSW in under 5 minutes. Please see the instructions below.
Once you have the library installed and running we highly recommend picking a tutorial on the relevant API you would be mocking:
Conventional API mocking suffers from the following pain-points:
Relies on a dedicated mocking server that you have to run and maintain;
There is no actual mocking in place: instead you replace requests' URL to point to the mocking server that seemingly behaves as the production one;
Brings extra dependencies to your application when it should have been a plain development tool.
MSW is immune to those drawbacks as its mocking principle doesn't revolve around servers.
MSW uses a Service Worker API with its ability to intercepts requests for the purpose of caching. Only, instead of caching MSW matches a dispatched request against a mocking schema and returns a mocked response upon match.
The primary benefit of using Service Workers for mocking is the ability to request the very same resources the client would in production. Since MSW performs "request-response" matching, there is no need for you to define conditional requests URL for the sake of mocking. It's enough to enable/disable the MSW to control whether the mocking should happen.
A response resolver function contains information about the request that took place, so you can perform the actual request and patch its response with the mocked data, if needed.
Such mocking technique is called "response patching" and you can read about it in the respective section of this documentation.
This library is meant to be used for development only. It doesn't require, nor encourage you to install any Service Worker on production environment.