Registry / testing / msw-storybook-addon

msw-storybook-addon

JSON →
library2.0.7jsnpmunverified

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-addon
INSTALL
IMPORT
SIG · MSW-STORYBOOK-ADDO
M
msw-storybook-addon
testingjavascriptv2.0.7
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

initialize
import { initialize } from 'msw-storybook-addon';
const initialize = require('msw-storybook-addon').initialize;
Used to set up the MSW service worker globally in Storybook's `preview.ts` or `preview.js` file.
mswLoader
import { mswLoader } from 'msw-storybook-addon';
import { mswDecorator } from 'msw-storybook-addon';
This is the recommended approach for applying MSW handlers to stories, replacing the deprecated `mswDecorator` since v2.0.0. It should be applied globally in `preview.ts` or per-story.
mswDecorator
import { mswDecorator } from 'msw-storybook-addon';
Deprecated since v2.0.0 and explicitly marked `@deprecated` in v2.0.6. While it still functions, `mswLoader` is the preferred and more robust method for new projects and migrations due to better integration with Storybook's modern rendering architecture.
MswParameters
import type { MswParameters } from 'msw-storybook-addon';
TypeScript type definition for configuring MSW parameters within Storybook stories, typically used for the `msw` property in Storybook's `parameters` object.

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.

import type { Meta, StoryObj } from '@storybook/react'; import { http, HttpResponse } from 'msw'; import { initialize, mswLoader } from 'msw-storybook-addon'; import { within, expect } from '@storybook/test'; // Assuming a simple React component that fetches user data const UserProfile = () => { const [user, setUser] = React.useState(null); React.useEffect(() => { fetch('/api/user') .then(res => res.json()) .then(data => setUser(data)); }, []); if (!user) return <div>Loading user...</div>; return ( <div> <h1>User Profile</h1> <p>Name: {user.name}</p> <p>Email: {user.email}</p> </div> ); }; // --- Configure in .storybook/preview.ts (or .js) --- // initialize({ // onUnhandledRequest: 'bypass', // }); // export const loaders = [mswLoader]; // --------------------------------------------------- const meta: Meta<typeof UserProfile> = { title: 'Components/UserProfile', component: UserProfile, parameters: { // Default MSW handlers for all stories under this meta msw: { handlers: [ http.get('/api/user', () => { return HttpResponse.json({ name: 'John Doe', email: 'john.doe@example.com' }); }), ], }, }, // Apply mswLoader globally to ensure mocks are active loaders: [mswLoader] }; export default meta; type Story = StoryObj<typeof UserProfile>; export const DefaultUser: Story = { play: async ({ canvasElement }) => { const canvas = within(canvasElement); await canvas.findByText('Name: John Doe'); await expect(canvas.findByText('Email: john.doe@example.com')).toBeInTheDocument(); }, }; export const AdminUser: Story = { parameters: { msw: { handlers: [ // Override specific handlers for this story http.get('/api/user', () => { return HttpResponse.json({ name: 'Admin User', email: 'admin@example.com', role: 'admin' }); }), ], }, }, play: async ({ canvasElement }) => { const canvas = within(canvasElement); await canvas.findByText('Name: Admin User'); await expect(canvas.findByText('Email: admin@example.com')).toBeInTheDocument(); }, };
Debug
Known issues
breakingVersion 2.0.0 of `msw-storybook-addon` introduced a breaking change requiring MSW version 2.0.0 or higher. Existing projects using MSW v1.x will need to migrate their MSW handlers to the v2.x format.
fix
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`).
affects: >=2.0.0
deprecatedThe `mswDecorator` has been deprecated in favor of `mswLoader` since v2.0.0. While `mswDecorator` may still function, `mswLoader` offers better integration with Storybook's modern architecture and lifecycle.
fix
Replace `addDecorator(mswDecorator)` with `loaders: [mswLoader]` in your Storybook `preview.ts` or individual story `meta` or `StoryObj` configurations.
affects: >=2.0.0
gotchaFor browser environments, MSW requires a Service Worker file (`mockServiceWorker.js`) to be present and correctly registered. If mocks are not working, ensure this file is served correctly from your public directory and `initialize()` is called.
fix
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.
affects: >=1.0.0
gotchaIncorrectly configuring the addon in Storybook's `main.js` or `main.ts` can lead to the addon not being active or not exposing its functionalities (like the `mswLoader`).
fix
Ensure `'msw-storybook-addon'` is correctly listed in the `addons` array in your `.storybook/main.js` or `.storybook/main.ts` configuration file.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: handler.isMiddleware is not a function
This error typically occurs when using MSW v1.x handler syntax with an MSW v2.x setup, which `msw-storybook-addon` v2.x requires.
fix
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.
Error: [MSW] Failed to register a Service Worker. This can happen if the 'msw' package is not installed or the 'mockServiceWorker.js' file is not found.
The MSW Service Worker (required for browser mocking) could not be registered, often due to the `mockServiceWorker.js` file being missing, incorrectly placed, or inaccessible.
fix
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`.
Property 'msw' does not exist on type 'Parameters<typeof C>'
This TypeScript error indicates that Storybook's `Parameters` type is not aware of the `msw` property, typically because the addon's types haven't been merged correctly.
fix
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.
Upgrade
Version history
2.0.7latest on npm
Audit
Dependencies
mswrequiredRequired peer dependency for the core mocking functionality, as the addon leverages MSW's network interception directly.
Agent activity
4 hits · last 30 days
node
4
Resources
msw-storybook-addon — npm install msw-storybook-addon · libregistry