The `msw-storybook-addon` package provides a seamless integration between Storybook and Mock Service Worker (MSW), allowing developers to effectively mock API requests directly within their Storybook stories. This integration is crucial for isolated component development, enabling consistent testing environments, and showcasing various data states without requiring a live backend or complex setup. The current stable version is 2.0.7, with the project maintaining an active release cadence, frequently publishing bug fixes and minor enhancements. Its key differentiator lies in its ability to leverage MSW's powerful network interception capabilities, applying mock handlers globally across all stories or specifically overriding them on a per-story basis. This flexibility is achieved using Storybook's parameters and loaders system, facilitating robust mocking for REST, GraphQL, and other network protocols in both browser and Node.js environments. It simplifies the creation of reproducible UI states dependent on API responses.
npm install msw-storybook-addonVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up `msw-storybook-addon` and define MSW handlers globally for a component's stories, as well as how to override handlers on a per-story basis. It also shows a basic Storybook `play` function to verify the mocked data.
Upgrade your `msw` package to `^2.0.0` and migrate your request handlers according to the MSW 1.x to 2.x migration guide (e.g., `rest` is now `http`).
Replace `addDecorator(mswDecorator)` with `loaders: [mswLoader]` in your Storybook `preview.ts` or individual story `meta` or `StoryObj` configurations.
Run `npx msw init <YOUR_PUBLIC_DIR>` (e.g., `npx msw init public`) to create the Service Worker file. Ensure `initialize()` is called in `.storybook/preview.ts` (or `.js`). Verify the file is accessible in your browser's developer tools.
Ensure `'msw-storybook-addon'` is correctly listed in the `addons` array in your `.storybook/main.js` or `.storybook/main.ts` configuration file.
Update your MSW handlers to the v2.x format. For instance, `rest.get` becomes `http.get`, and handlers return `HttpResponse` instead of plain objects. Refer to the MSW migration guide.
Run `npx msw init <YOUR_PUBLIC_DIR>` (e.g., `npx msw init public`) to generate the service worker. Ensure it's in a path accessible by your web server/Storybook. Also, confirm `initialize({ onUnhandledRequest: 'bypass' })` is called in `.storybook/preview.ts`.Ensure `import type { MswParameters } from 'msw-storybook-addon';` is present and that your Storybook type definitions are set up to extend `Parameters` correctly, for example, by adding `msw-storybook-addon` to your `tsconfig.json`'s `types` array or by directly importing `MswParameters` where needed.