MSW (Mock Service Worker) is an API mocking library that operates by intercepting production requests.
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:
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.
Keep in mind that Service Workers is a browser API, which makes MSW usable on the client-side only. You won't be able to use such mocking when hitting a mocked URL via
curl, for example.
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.
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.