Mocking providers

The context provider pattern and how to mock it only applies to renderers that use JSX, like React or Solid.

Components can receive data or configuration from context providers. For example, a styled component might access its theme from a ThemeProvider or Redux uses React context to provide components access to app data. To mock a provider, you can wrap your component in a decorator that includes the necessary context.

Note the file extension above (.tsx or .jsx). You may need to adjust your preview file's extension to allow use of JSX, depending on your project's settings.

For another example, reference the Screens chapter of the Intro to Storybook tutorial, where we mock a Redux provider with mock data.

Configuring the mock provider

When mocking a provider, it may be necessary to configure the provider to supply a different value for individual stories. For example, you might want to test a component with different themes or user roles.

One way to do this is to define the decorator for each story individually. But if you imagine a scenario where you wish to create stories for each of your components in both light and dark themes, this approach can quickly become cumbersome.

For a better way, with much less repetition, you can use the decorator function's second "context" argument to access a story's parameters and adjust the provided value. This way, you can define the provider once and adjust its value for each story.

For example, we can adjust the decorator from above to read from parameters.theme to determine which theme to provide:

Now, you can define a theme parameter in your stories to adjust the theme provided by the decorator:

This powerful approach allows you to provide any value (theme, user role, mock data, etc.) to your components in a way that is both flexible and maintainable.

Was this page helpful?

Markdown accepted ([link text](url), _italic_, **bold**, etc). Your anonymous feedback will be posted publicly on GitHub.

✍️ Edit on GitHub – PRs welcome!
Storybook
Join the community
6,616 developers and counting
WhyWhy StorybookComponent-driven UI
DocsGuidesTutorialsChangelogTelemetry
CommunityAddonsGet involvedBlog
ShowcaseExploreProjectsComponent glossary
Open source software
Storybook

Maintained by
Chromatic
Special thanks to Netlify and CircleCI