All Projects → mswjs → msw-storybook-addon

mswjs / msw-storybook-addon

Licence: MIT License
Mock API requests in Storybook with Mock Service Worker.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
HTML
75241 projects
CSS
56736 projects

Projects that are alternatives of or similar to msw-storybook-addon

Storybook Addon Jest
REPO/PACKAGE MOVED - React storybook addon that show component jest report
Stars: ✭ 177 (+5.36%)
Mutual labels:  addon, storybook
storybook-styled-components
No description or website provided.
Stars: ✭ 76 (-54.76%)
Mutual labels:  addon, storybook
Addon Jsx
This Storybook addon show you the JSX / template of the story
Stars: ✭ 209 (+24.4%)
Mutual labels:  addon, storybook
Storybook Addon
Develop themable components with Emotion/Styled Components/Material-UI with help of Storybook & React Theming
Stars: ✭ 122 (-27.38%)
Mutual labels:  addon, storybook
mswjs.io
Official website and documentation for the Mock Service Worker library.
Stars: ✭ 77 (-54.17%)
Mutual labels:  mock, msw
React Storybook Addon Props Combinations
Given possible values for each prop, renders your component with all combinations of prop values.
Stars: ✭ 130 (-22.62%)
Mutual labels:  addon, storybook
Msw
Seamless REST/GraphQL API mocking library for browser and Node.js.
Stars: ✭ 7,830 (+4560.71%)
Mutual labels:  mock, msw
Storycap
A Storybook Addon, Save the screenshot image of your stories 📷 via puppeteer.
Stars: ✭ 451 (+168.45%)
Mutual labels:  addon, storybook
storybook-addon-next
A no config Storybook addon that makes Next.js features just work in Storybook
Stars: ✭ 184 (+9.52%)
Mutual labels:  addon, storybook
storybook-xstate-addon
A storybook addon to assist with writing stories that rely on xstate
Stars: ✭ 48 (-71.43%)
Mutual labels:  addon, storybook
Storybook Addon Preview
Storybook Addon Preview can show user selected knobs in various framework code in Storybook
Stars: ✭ 43 (-74.4%)
Mutual labels:  addon, storybook
create-material-ui-app
create-react-app + storybook + storybook-addon-material-ui
Stars: ✭ 55 (-67.26%)
Mutual labels:  addon, storybook
Storybook Addon A11y
REPO/PACKAGE MOVED - Storybook addon to help, improving accessibility within you're react components.
Stars: ✭ 37 (-77.98%)
Mutual labels:  addon, storybook
Storybook Addon Styled Component Theme
storybook addon
Stars: ✭ 168 (+0%)
Mutual labels:  addon, storybook
Storybook Addon Material Ui
Addon for storybook wich wrap material-ui components into MuiThemeProvider. 📃 This helps and simplifies development of material-ui based components.
Stars: ✭ 513 (+205.36%)
Mutual labels:  addon, storybook
Addon Smart Knobs
🧠 This Storybook plugin uses @storybook/addon-knobs but creates the knobs automatically based on PropTypes.
Stars: ✭ 215 (+27.98%)
Mutual labels:  addon, storybook
React Nativeish
React Native / React Native Web Boilerplate
Stars: ✭ 106 (-36.9%)
Mutual labels:  mock, storybook
storybook-addon-mock
This addon allows you to mock fetch or XMLHttpRequest in the storybook.
Stars: ✭ 67 (-60.12%)
Mutual labels:  addon, storybook
storybook-addon-headless
A Storybook addon to preview content from a headless CMS in components
Stars: ✭ 23 (-86.31%)
Mutual labels:  addon, storybook
SyncMarks-Extension
Browser Webextension for Firefox, Edge or Chromium derivatives to sync your bookmarks with a private backend.
Stars: ✭ 23 (-86.31%)
Mutual labels:  addon

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, mswDecorator } from 'msw-storybook-addon';

// Initialize MSW
initialize();

// Provide the MSW addon decorator globally
export const decorators = [mswDecorator];

Start Storybook

When running Storybook, you have to serve the public folder as an asset to Storybook. Refer to the docs if needed.

npm run start-storybook -s public

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
      `)
    }
  },
})
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].