{"library":"msw-storybook-addon","title":"MSW Storybook Addon","description":"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.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install msw-storybook-addon"],"cli":null},"imports":["import { initialize } from 'msw-storybook-addon';","import { mswLoader } from 'msw-storybook-addon';","import { mswDecorator } from 'msw-storybook-addon';","import type { MswParameters } from 'msw-storybook-addon';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import type { Meta, StoryObj } from '@storybook/react';\nimport { http, HttpResponse } from 'msw';\nimport { initialize, mswLoader } from 'msw-storybook-addon';\nimport { within, expect } from '@storybook/test';\n\n// Assuming a simple React component that fetches user data\nconst UserProfile = () => {\n  const [user, setUser] = React.useState(null);\n  React.useEffect(() => {\n    fetch('/api/user')\n      .then(res => res.json())\n      .then(data => setUser(data));\n  }, []);\n\n  if (!user) return <div>Loading user...</div>;\n  return (\n    <div>\n      <h1>User Profile</h1>\n      <p>Name: {user.name}</p>\n      <p>Email: {user.email}</p>\n    </div>\n  );\n};\n\n// --- Configure in .storybook/preview.ts (or .js) ---\n// initialize({\n//   onUnhandledRequest: 'bypass',\n// });\n// export const loaders = [mswLoader];\n// ---------------------------------------------------\n\nconst meta: Meta<typeof UserProfile> = {\n  title: 'Components/UserProfile',\n  component: UserProfile,\n  parameters: {\n    // Default MSW handlers for all stories under this meta\n    msw: {\n      handlers: [\n        http.get('/api/user', () => {\n          return HttpResponse.json({ name: 'John Doe', email: 'john.doe@example.com' });\n        }),\n      ],\n    },\n  },\n  // Apply mswLoader globally to ensure mocks are active\n  loaders: [mswLoader]\n};\n\nexport default meta;\n\ntype Story = StoryObj<typeof UserProfile>;\n\nexport const DefaultUser: Story = {\n  play: async ({ canvasElement }) => {\n    const canvas = within(canvasElement);\n    await canvas.findByText('Name: John Doe');\n    await expect(canvas.findByText('Email: john.doe@example.com')).toBeInTheDocument();\n  },\n};\n\nexport const AdminUser: Story = {\n  parameters: {\n    msw: {\n      handlers: [\n        // Override specific handlers for this story\n        http.get('/api/user', () => {\n          return HttpResponse.json({ name: 'Admin User', email: 'admin@example.com', role: 'admin' });\n        }),\n      ],\n    },\n  },\n  play: async ({ canvasElement }) => {\n    const canvas = within(canvasElement);\n    await canvas.findByText('Name: Admin User');\n    await expect(canvas.findByText('Email: admin@example.com')).toBeInTheDocument();\n  },\n};\n","lang":"typescript","description":"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}