Skip to content
Seamless REST/GraphQL API mocking library for browser and Node.
TypeScript JavaScript CSS HTML
Branch: master
Clone or download

Latest commit

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.circleci Runs lint on CI build May 24, 2020
.github Updates CONTRIBUTING guidelines May 24, 2020
cli Renames "cli/msw.js" to "cli/index.js" May 2, 2020
config Configures build to point to the built service worker May 7, 2020
media Adds SVG logo to the media resources Jun 7, 2020
node Builds a node bundle into "node" directory May 16, 2020
src add realistic server response delay to ctx.delay() Jun 5, 2020
test spawnServer: Disables hot reloading for test runs Jun 4, 2020
.eslintrc.js setupWorker: Supports runtime request handlers May 30, 2020
.gitignore Builds a node bundle into "node" directory May 16, 2020
.nvmrc Fixes node version to v10.18.1 Apr 20, 2020
.prettierrc Response: Adopts functional composition of "res" Nov 18, 2018
LICENSE.md Adds LICENSE Nov 15, 2018
README.md Forwards to the examples repo from the README May 17, 2020
babel.config.js Updates dependencies, removes ramda dependencies Apr 29, 2020
global.d.ts Extends "start" options to support "quiet" Apr 22, 2020
jest.config.js composeMocks: Adds unit tests Mar 9, 2019
jest.setup.js Uses "Headers" and "serviceWorker" definition in browser-like tests only Jun 4, 2020
logo.png Updates the logo subtitle May 18, 2020
package.json v0.19.0 Jun 4, 2020
rollup.config.ts Lists "node-request-interceptor" as an external dependency May 24, 2020
tsconfig.json Splits bundle into mutliple entries to support tree shaking May 7, 2020
yarn.lock Bump websocket-extensions from 0.1.3 to 0.1.4 Jun 8, 2020

README.md

Package version Build status Dependencies status Dev dependencies status

Mock Service Worker (MSW) is an API mocking library for browser and Node that intercepts outgoing requests using Service Workers.

Features

  • Server-less. Mocking that doesn't establish any servers, operating entirely in a browser;
  • Seamless. Forget about stubs and hacks that make your code smell. Leverage a dedicated layer of interception to keep your code clean and shiny.
  • Deviation-free. Request the same resources you would in production, and mock their responses. No more conditional URLs, no more mock-specific parts of code in your app.
  • Mocking as a tool. Enable, change, disable mocking on runtime instantly without any compilations or rebuilds. Control the MSW lifecycle from your browser's DevTools;
  • Essentials. Use Express-like syntax to define which requests to mock. Respond with custom status codes, headers, delays, or create custom response resolvers.

"This is awesome."

Kent C. Dodds

Documentation

Quick start

Install the library in your project:

$ npm install msw

Copy the Service Worker file that's responsible for requests interception. Use a designated CLI to do that (from your project's root directory):

$ npx msw init <PUBLIC_DIR>

Provide the path to your public directory instead of the <PUBLIC_DIR> placeholder above. Your public directory is usually a directory being served by a server (i.e. ./public or ./dist). Running this command will place the mockServiceWorker.js file into given directory.

For example, in Create React App you would run: npx msw init ./public

Once the Service Worker has been copied, we can continue with creating a mocking definition file. For the purpose of this short tutorial we are going to keep all our mocking logic in the mocks.js file, but the end file structure is up to you.

$ touch mocks.js

Open that file and follow the example below to create your first mocking definition:

// mocks.js
// 1. Import mocking utils
import { setupWorker, rest } from 'msw'

// 2. Define request handlers and response resolvers
const worker = setupWorker(
  rest.get('https://github.com/octocat', (req, res, ctx) => {
    return res(
      ctx.delay(1500),
      ctx.status(202, 'Mocked status'),
      ctx.json({
        message: 'This is a mocked error',
      }),
    )
  }),
)

// 3. Start the Service Worker
worker.start()

Import the mocks.js module into your application to enable the mocking. You can import the mocking definition file conditionally, so it's never loaded on production:

// src/index.js
if (process.env.NODE_ENV === 'development') {
  require('./mocks')
}

Verify the MSW is running by seeing a successful Service Worker activation message in the browser's console. Now any outgoing request of your application are intercepted by the Service Worker, signaled to the client-side library, and matched against the mocking definition. If a request matches any definition, its response is being mocked and returned to the browser.

Chrome DevTools Network screenshot with the request mocked

Notice the 202 Mocked status (from ServiceWorker) status in the response.

We have prepared a set of step-by-step tutorials to get you started with mocking the API type you need. For example, did you know you can mock a GraphQL API using MSW? Find detailed instructions in the respective tutorials below.

Tutorials

Examples

You can’t perform that action at this time.