Mock Service Worker

Seamless REST/GraphQL API mocking library for browser and Node.js.

README


Mock Service Worker logo

Mock Service Worker

Mock Service Worker (MSW) is a seamless REST/GraphQL API mocking library for browser and Node.js.

Package version Downloads per month Discord server


Features


- Seamless. A dedicated layer of requests interception at your disposal. Keep your application's code and tests unaware of whether something is mocked or not.
- Deviation-free. Request the same production resources and test the actual behavior of your app. Augment an existing API, or design it as you go when there is none.
- Familiar & Powerful. Use Express-like routing syntax to capture requests. Use parameters, wildcards, and regular expressions to match requests, and respond with necessary status codes, headers, cookies, delays, or completely custom resolvers.


"_I found MSW and was thrilled that not only could I still see the mocked responses in my DevTools, but that the mocks didn't have to be written in a Service Worker and could instead live alongside the rest of my app. This made it silly easy to adopt. The fact that I can use it for testing as well makes MSW a huge productivity booster._"

>

Documentation


This README will give you a brief overview on the library but there's no better place to start with Mock Service Worker than its official documentation.

- [Getting started](https://mswjs.io/docs/getting-started/install)
- FAQ

Examples


- See the list of [Usage examples](https://github.com/mswjs/examples)

Browser


- [setupWorker API](https://mswjs.io/docs/api/setup-worker)

How does it work?


In-browser usage is what sets Mock Service Worker apart from other tools. Utilizing the Service Worker API, which can intercept requests for the purpose of caching, Mock Service Worker responds to captured requests with your mock definition on the network level. This way your application knows nothing about the mocking.

Take a look at this quick presentation on how Mock Service Worker functions in a browser:
What is Mock Service Worker?

How is it different?


- This library intercepts requests on the network level, which means _after_ they have been performed and "left" your application. As a result, the entirety of your code runs, giving you more confidence when mocking;
- Imagine your application as a box. Every API mocking library out there opens your box and removes the part that does the request, placing a blackbox in its stead. Mock Service Worker leaves your box intact, 1-1 as it is in production. Instead, MSW lives in a separate box next to yours;
- No more stubbing of fetch, axios, react-query, you-name-it;
- You can reuse the same mock definition for the unit, integration, and E2E testing. Did we mention local development and debugging? Yep. All running against the same network description without the need for adapters of bloated configurations.

Usage example


  1. ``` js
  2. // src/mocks.js
  3. // 1. Import the library.
  4. import { setupWorker, rest } from 'msw'

  5. // 2. Describe network behavior with request handlers.
  6. const worker = setupWorker(
  7.   rest.get('https://github.com/octocat', (req, res, ctx) => {
  8.     return res(
  9.       ctx.delay(1500),
  10.       ctx.status(202, 'Mocked status'),
  11.       ctx.json({
  12.         message: 'Mocked response JSON body',
  13.       }),
  14.     )
  15.   }),
  16. )

  17. // 3. Start request interception by starting the Service Worker.
  18. worker.start()
  19. ```

Performing a GET https://github.com/octocat request in your application will result into a mocked response that you can inspect in your browser's "Network" tab:

Chrome DevTools Network screenshot with the request mocked

Tip: Did you know that although Service Worker runs in a separate thread, your mock definition executes entirely on the client? This way you can use the same languages, like TypeScript, third-party libraries, and internal logic to create the mocks you need.


Node.js


- [setupServer API](https://mswjs.io/docs/api/setup-server)

How does it work?


There's no such thing as Service Workers in Node.js. Instead, MSW implements a low-level interception algorithm that can utilize the very same request handlers you have for the browser. This blends the boundary between environments, allowing you to focus on your network behaviors.

How is it different?


- Does not stub fetch, axios, etc. As a result, your tests know _nothing_ about mocking;
- You can reuse the same request handlers for local development and debugging, as well as for testing. Truly a single source of truth for your network behavior across all environments and all tools.

Usage example


Take a look at the example of an integration test in Jest that uses React Testing Library and Mock Service Worker:

  1. ``` js
  2. // test/Dashboard.test.js

  3. import React from 'react'
  4. import { rest } from 'msw'
  5. import { setupServer } from 'msw/node'
  6. import { render, screen, waitFor } from '@testing-library/react'
  7. import Dashboard from '../src/components/Dashboard'

  8. const server = setupServer(
  9.   // Describe network behavior with request handlers.
  10.   // Tip: move the handlers into their own module and
  11.   // import it across your browser and Node.js setups!
  12.   rest.get('/posts', (req, res, ctx) => {
  13.     return res(
  14.       ctx.json([
  15.         {
  16.           id: 'f8dd058f-9006-4174-8d49-e3086bc39c21',
  17.           title: `Avoid Nesting When You're Testing`,
  18.         },
  19.         {
  20.           id: '8ac96078-6434-4959-80ed-cc834e7fef61',
  21.           title: `How I Built A Modern Website In 2021`,
  22.         },
  23.       ]),
  24.     )
  25.   }),
  26. )

  27. // Enable request interception.
  28. beforeAll(() => server.listen())

  29. // Reset handlers so that each test could alter them
  30. // without affecting other, unrelated tests.
  31. afterEach(() => server.resetHandlers())

  32. // Don't forget to clean up afterwards.
  33. afterAll(() => server.close())

  34. it('displays the list of recent posts', async () => {
  35.   render(<Dashboard />)

  36.   // 🕗 Wait for the posts request to be finished.
  37.   await waitFor(() => {
  38.     expect(
  39.       screen.getByLabelText('Fetching latest posts...'),
  40.     ).not.toBeInTheDocument()
  41.   })

  42.   // ✅ Assert that the correct posts have loaded.
  43.   expect(
  44.     screen.getByRole('link', { name: /Avoid Nesting When You're Testing/ }),
  45.   ).toBeVisible()

  46.   expect(
  47.     screen.getByRole('link', { name: /How I Built A Modern Website In 2021/ }),
  48.   ).toBeVisible()
  49. })
  50. ```

Don't get overwhelmed! We've prepared a step-by-step [Getting started](https://mswjs.io/docs/getting-started/install) tutorial that you can follow to learn how to integrate Mock Service Worker into your project.


Despite the API being called setupServer, there are no actual servers involved! The name was chosen for familiarity, and the API was designed to resemble operating with an actual server.

Sponsors


Mock Service Worker is trusted by hundreds of thousands of engineers around the globe. It's used by companies like Google, Microsoft, Spotify, Amazon, and countless others. Despite that, this library remains a hobby project maintained in spare time and has no opportunity to financially support even a single full-time contributor.

You can change that! Consider sponsoring the effort behind one of the most innovative approaches around API mocking. Raise a topic of open source sponsorships with your boss and colleagues. Let's build sustainable open source together!

Golden Sponsors


Become our first golden sponsor and get featured right here, enjoying other perks like issue prioritization and a personal consulting session with us.

>

Learn more on our GitHub Sponsors profile.


GitHub

Silver Sponsors


Become our _silver sponsor_ and get your profile image and link featured right here.

>

Learn more on our GitHub Sponsors profile.


Chromatic

Bronze Sponsors


Become our first _bronze sponsor_ and get your profile image and link featured in this section.

>

Learn more on our GitHub Sponsors profile.


Awards & Mentions


We've been extremely humbled to receive awards and mentions from the community for all the innovation and reach Mock Service Worker brings to the JavaScript ecosystem.

Technology Radar

Solution Worth Pursuing

Technology Radar (2020–2021)

Open Source Awards 2020

The Most Exciting Use of Technology

Open Source Awards (2020)