FunnyLiu / msw

Client-side API mocking using Service Workers.

Home Page:https://redd.gitbook.io/msw

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Package version Build status Dependencies status Dev dependencies status

MSW

Mock Service Worker (MSW) is a client-side API mocking library that operates by intercepting outgoing requests using Service Workers.

Features

  • Server-less. Doesn't establish any servers, operating entirely in a browser;
  • Deviation-free. Intercepts production URI requests from your page and mocks their responses, without having to deal with mocked URI.
  • 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 look

$ npm install msw --save-dev

Now we have to put the mockServiceWorker.js file in your public directory. That is usually a directory being served by your server (i.e. public/ or dist/). The placing of the file is done by running the following command from your project's root directory:

$ npx msw init <PUBLIC_DIR>

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

MSW workflow consist of three phases:

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

// 2. Define request handlers and response resolvers
const { start } = composeMocks(
  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
start()

Import the mocks.js module into your application to enable the mocking.

// src/index.js
import './mocks'

Once enabled, any requests matching the defined paths will be intercepted by Service Worker, which would respond with mocked responses.

Chrome DevTools Network screenshot with the request mocked

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

There is a set of step-by-step tutorials to get you started with mocking the API type you need. Please refer to those tutorials below for more detailed instructions.

Tutorials

Examples

About

Client-side API mocking using Service Workers.

https://redd.gitbook.io/msw

License:MIT License


Languages

Language:TypeScript 68.1%Language:JavaScript 31.9%