Storybook helps you build any component, from small “atomic” components to composed pages. But as you move up the component hierarchy toward the page level, you deal with more complexity.
There are many ways to build pages in Storybook. Here are common patterns and solutions.
- Pure presentational pages.
- Connected components (e.g., network requests, context, browser environment).
Pure presentational pages
Teams at the BBC, The Guardian, and the Storybook maintainers themselves build pure presentational pages. If you take this approach, you don't need to do anything special to render your pages in Storybook.
It's straightforward to write components to be fully presentational up to the screen level. That makes it easy to show in Storybook. The idea is that you do all the messy “connected” logic in a single wrapper component in your app outside of Storybook. You can see an example of this approach in the Data chapter of the Intro to Storybook tutorial.
The benefits:
- Easy to write stories once components are in this form.
- All the data for the story is encoded in the args of the story, which works well with other parts of Storybook's tooling (e.g. controls).
The downsides:
-
Your existing app may not be structured in this way, and it may be difficult to change it.
-
Fetching data in one place means that you need to drill it down to the components that use it. This can be natural in a page that composes one big GraphQL query (for instance), but other data fetching approaches may make this less appropriate.
-
It's less flexible if you want to load data incrementally in different places on the screen.
Args composition for presentational screens
When you are building screens in this way, it is typical that the inputs of a composite component are a combination of the inputs of the various sub-components it renders. For instance, if your screen renders a page layout (containing details of the current user), a header (describing the document you are looking at), and a list (of the subdocuments), the inputs of the screen may consist of the user, document and subdocuments.
In such cases, it is natural to use args composition to build the stories for the page based on the stories of the sub-components:
This approach is beneficial when the various subcomponents export a complex list of different stories. You can pick and choose to build realistic scenarios for your screen-level stories without repeating yourself. Your story maintenance burden is minimal by reusing the data and taking a Don't-Repeat-Yourself(DRY) philosophy.
Mocking connected components
If you need to render a connected component in Storybook, you can mock the network requests to fetch its data. There are various layers in which you can do that.
Mocking providers
Suppose you are using a provider that supplies data via the context. In that case, you can wrap your story in a decorator that provides a mocked version of that provider. For example, in the Screens chapter of the Intro to Storybook tutorial, we mock a Redux provider with mock data.
Mocking API Services
Connected applications such as Twitter, Instagram, amongst others, are everywhere, consuming data from REST or GraphQL endpoints. Suppose you're working in an application that relies on either of these data providers. In that case, you can add Mock Service Worker (MSW) via Storybook's MSW addon to mock data alongside your app and stories.
Mock Service Worker is an API mocking library. It relies on service workers to capture network requests and provides mocked data in response. The MSW addon adds this functionality into Storybook, allowing you to mock API requests in your stories. Below is an overview of how to set up and use the addon.
Run the following commands to install MSW, the addon, and generate a mock service worker.
If you're working with Angular, you'll need to adjust the command to save the mock service worker file in a different directory (e.g., src
).
Update your .storybook/preview.js
file and enable the addon via a global decorator.
Finally, update your .storybook/main.js|ts
to allow Storybook to load the generated mock service worker file as follows:
Mocking REST requests with MSW addon
If you're working with pure presentational screens, adding stories through args composition is recommended. You can easily encode all the data via args, removing the need for handling it with "wrapper components". However, this approach loses its flexibility if the screen's data is retrieved from a RESTful endpoint within the screen itself. For instance, if your screen had a similar implementation to retrieve a list of documents:
To test your screen with the mocked data, you could write a similar set of stories:
This example details how you can mock the REST request with fetch. Similar HTTP clients such as axios
can be used as well.
The mocked data (i.e., TestData
) will be injected via parameters, enabling you to configure it per-story basis.
Mocking GraphQL queries with MSW addon
In addition to mocking RESTful requests, the other noteworthy feature of the MSW addon is the ability to mock incoming data from any of the mainstream GraphQL clients (e.g., Apollo Client, URQL or React Query). For instance, if your screen retrieves the user's information and a list of documents based on a query result, you could have a similar implementation:
To test your screen with the GraphQL mocked data, you could write the following stories:
Mocking imports
It is also possible to mock imports directly, as you might in a unit test, using Webpack’s aliasing. It's advantageous if your component makes network requests directly with third-party libraries.
We'll use isomorphic-fetch as an example.
Inside a directory called __mocks__
, create a new file called
isomorphic-fetch.js
with the following code:
The code above creates a decorator which reads story-specific data off the story's parameters, enabling you to configure the mock on a per-story basis.
To use the mock in place of the real import, we use Webpack aliasing:
Add the decorator you've just implemented to your storybook/preview.js
:
Finally, we can set the mock values in a specific story. Let's borrow an example from this blog post:
Specific mocks
Another mocking approach is to use libraries that intercept calls at a lower level. For instance, you can use fetch-mock
to mock fetch requests specifically.
Like the import mocking above, once you have a mock, you’ll still want to set the return value of the mock per-story basis. Do this in Storybook with a decorator that reads the story's parameters.