What is msw-storybook-addon?
The msw-storybook-addon package is an addon for Storybook that integrates with Mock Service Worker (MSW) to mock API requests. It allows developers to create and manage mock API responses directly within Storybook, making it easier to develop and test UI components in isolation.
What are msw-storybook-addon's main functionalities?
Mocking API Requests
This feature allows you to mock API requests using MSW within Storybook. The code sample demonstrates how to initialize the addon, set up a decorator, and define a handler for a GET request to '/api/user'.
import { initialize, mswDecorator } from 'msw-storybook-addon';
import { rest } from 'msw';
initialize();
export const decorators = [
mswDecorator,
];
export const handlers = [
rest.get('/api/user', (req, res, ctx) => {
return res(ctx.json({ username: 'John Doe' }));
}),
];
Configuring Handlers Per Story
This feature allows you to configure different handlers for each story. The code sample shows how to set up a handler for a specific story, overriding the default handler for the '/api/user' endpoint.
import { rest } from 'msw';
export default {
title: 'Example/Button',
parameters: {
msw: [
rest.get('/api/user', (req, res, ctx) => {
return res(ctx.json({ username: 'Jane Doe' }));
}),
],
},
};
const Template = (args) => <Button {...args} />;
export const Primary = Template.bind({});
Primary.args = {
label: 'Button',
};
Logging and Debugging
This feature provides logging and debugging capabilities for unhandled requests. The code sample demonstrates how to initialize the addon with a configuration that logs warnings for unhandled requests.
import { initialize, mswDecorator } from 'msw-storybook-addon';
initialize({ onUnhandledRequest: 'warn' });
export const decorators = [
mswDecorator,
];
Other packages similar to msw-storybook-addon
storybook-addon-mock
storybook-addon-mock is a Storybook addon that allows you to mock API requests and responses. It provides a similar functionality to msw-storybook-addon but uses a different approach for defining and managing mocks. It is less integrated with MSW and may require more manual setup.
storybook-addon-apollo-client
storybook-addon-apollo-client is an addon for Storybook that integrates with Apollo Client to mock GraphQL queries and mutations. While it focuses on GraphQL rather than REST APIs, it provides similar capabilities for mocking API responses within Storybook.