• Stars
    star
    392
  • Rank 109,735 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mock API requests in Storybook with Mock Service Worker.

MSW Storybook Addon

Features

  • Mock Rest and GraphQL requests right inside your story.
  • Document how a component behaves in various scenarios.
  • Get a11y, snapshot and visual tests using other addons for free.

Full documentation and live demos

Installing and Setup

Install MSW and the addon

With npm:

npm i msw msw-storybook-addon -D

Or with yarn:

yarn add msw msw-storybook-addon -D

Generate service worker for MSW in your public folder.

If you already use MSW in your project, you have likely done this before so you can skip this step.

npx msw init public/

Refer to the MSW official guide for framework specific paths if you don't use public.

Configure the addon

Enable MSW in Storybook by initializing MSW and providing the MSW decorator in ./storybook/preview.js:

import { initialize, mswLoader } from 'msw-storybook-addon';

// Initialize MSW
initialize();

const preview = {
  parameters: { 
    // your other code...
  },
  // Provide the MSW addon loader globally
  loaders: [mswLoader],
}

export default preview

Start Storybook

When running Storybook, you have to serve the public folder as an asset to Storybook, so that MSW is included, otherwise it will not be available in the browser.

This means you should set the staticDirs field in the Storybook main config file. Refer to the docs if needed.

npm run start-storybook

Usage

You can pass request handlers (https://mswjs.io/docs/basics/request-handler) into the handlers property of the msw parameter. This is commonly an array of handlers.

import { rest } from 'msw'

export const SuccessBehavior = () => <UserProfile />

SuccessBehavior.parameters = {
  msw: {
    handlers: [
      rest.get('/user', (req, res, ctx) => {
        return res(
          ctx.json({
            firstName: 'Neil',
            lastName: 'Maverick',
          })
        )
      }),
    ]
  },
}

Advanced Usage

Composing request handlers

The handlers property can also be an object where the keys are either arrays of handlers or a handler itself. This enables you to inherit (and optionally overwrite/disable) handlers from preview.js using parameter inheritance:

type MswParameter = {
  handlers: RequestHandler[] | Record<string, RequestHandler | RequestHandler[]>
}

Suppose you have an application where almost every component needs to mock requests to /login and /logout the same way. You can set global MSW handlers in preview.js for those requests and bundle them into a property called auth, for example:

//preview.js

// These handlers will be applied in every story
export const parameters = {
   msw: {
      handlers: {
        auth: [
           rest.get('/login', (req, res, ctx) => {
              return res(
                ctx.json({
                   success: true,
                })
              )
           }),
           rest.get('/logout', (req, res, ctx) => {
              return res(
                ctx.json({
                   success: true,
                })
              )
           }),
        ],
      }
   }
};

Then, you can use other handlers in your individual story. Storybook will merge both global handlers and story handlers:

// This story will include the auth handlers from preview.js and profile handlers
SuccessBehavior.parameters = {
  msw: {
   handlers: {
    profile: rest.get('/profile', (req, res, ctx) => {
      return res(
       ctx.json({
        firstName: 'Neil',
        lastName: 'Maverick',
       })
      )
    }),
   }
  }
}

Now suppose you want to ovewrite the global handlers for auth. All you have to do is set them again in your story and these values will take precedence:

// This story will overwrite the auth handlers from preview.js
FailureBehavior.parameters = {
  msw: {
   handlers: {
    auth: rest.get('/login', (req, res, ctx) => {
      return res(ctx.status(403))
    }),
   }
  }
}

What if you want to disable global handlers? All you have to do is set them as null and they will be ignored for your story:

// This story will disable the auth handlers from preview.js
NoAuthBehavior.parameters = {
  msw: {
   handlers: {
    auth: null,
    others: [
      rest.get('/numbers', (req, res, ctx) => {
       return res(ctx.json([1, 2, 3]))
      }),
      rest.get('/strings', (req, res, ctx) => {
       return res(ctx.json(['a', 'b', 'c']))
      }),
    ],
   }
  }
}

Configuring MSW

msw-storybook-addon starts MSW with default configuration. If you want to configure it, you can pass options to the initialize function. They are the StartOptions from setupWorker.

A common example is to configure the onUnhandledRequest behavior, as MSW logs a warning in case there are requests which were not handled.

If you want MSW to bypass unhandled requests and not do anything:

// preview.js
import { initialize } from 'msw-storybook-addon';

initialize({
  onUnhandledRequest: 'bypass'
})

If you want to warn a helpful message in case stories make requests that should be handled but are not:

// preview.js
import { initialize } from 'msw-storybook-addon';

initialize({
  onUnhandledRequest: ({ method, url }) => {
    if (url.pathname.startsWith('/my-specific-api-path')) {
      console.error(`Unhandled ${method} request to ${url}.

        This exception has been only logged in the console, however, it's strongly recommended to resolve this error as you don't want unmocked data in Storybook stories.

        If you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses
      `)
    }
  },
})

Troubleshooting

MSW is interfering with HMR (Hot Module Replacement)

If you're experiencing issues like [MSW] Failed to mock a "GET" request to "http://localhost:6006/4cb31fa2eee22cf5b32f.hot-update.json" in the console, it's likely that MSW is interfering with HMR. This is not common and it seems to only happen in Webpack projects, but if it happens to you, you can follow the steps in this issue to fix it:

#36 (comment)

More Repositories

1

msw

Industry standard API mocking for JavaScript.
TypeScript
15,862
star
2

data

Data modeling and relation library for testing JavaScript applications.
TypeScript
627
star
3

examples

Examples of Mock Service Worker usage with various frameworks and libraries.
JavaScript
565
star
4

interceptors

Low-level HTTP/HTTPS/XHR/fetch request interception library.
TypeScript
420
star
5

mswjs.io

Official website and documentation for the Mock Service Worker library.
TypeScript
154
star
6

source

Generate MSW request handlers from various sources (HAR files, OpenAPI documents, etc).
TypeScript
120
star
7

http-middleware

Spawn an HTTP server from your request handlers or apply them to an existing server using a middleware.
TypeScript
73
star
8

jest-fixed-jsdom

A superset of the JSDOM environment for Jest that respects Node.js globals.
JavaScript
30
star
9

node-match-path

Matches a URL against a path. Parameters, wildcards, RegExp.
TypeScript
30
star
10

headers-polyfill

A Fetch API "Headers" polyfill and transformation library.
TypeScript
27
star
11

cookies

Manage request/response cookies in the environments where those are not supported.
TypeScript
19
star
12

storage

Persistence and live synchronization layer for testing JavaScript applications.
TypeScript
16
star
13

is-node-process

Reliably determines if the code is running in Node.js. Treats Jest, React Native, Electron, and others like Node.js.
TypeScript
9
star
14

examples-new

6
star
15

gh-issue-forms

A test repository that is going to disappear.
Shell
4
star
16

msw-github-bot

Mock Service Worker community bot. Beep. Bop.
TypeScript
3
star
17

github-webhooks

TypeScript
1
star
18

local-storage-polyfill

The "localStorage" polyfill for Node.js.
TypeScript
1
star