This video is available to students only

Data fetching - Mocking Requests

Mocking fetch requests on Storybook.

Proxy and mock fetch requests#

Sometimes, components are not simple to separate into container and presentational components — think of pages, for instance. Sometimes, you want to have components doing data fetching on Storybook so they are as close as possible to their behavior in production. You might also want to be able to list all the possible states of a page in Storybook, such as success, error, 404, and loading.

In this case, rather than using strategies in client code as we've done in previous lessons, we can alter the behavior of the server instead, by proxying requests with a tool like MSW - Mock service worker.

MSW registers a service worker on the client, which will proxy all of the HTTP requests coming via the application, and if those requests match a configuration that we define, instead of going through to connect with the real backend, it will intercept them and make them use our local logic, returning the mocked data that we set instead.

However, this is not all. MSW also allows us to completely tinker with the request and change whatever we want in the response. For error scenarios, we can return a different status code. For loading scenarios, we can force a timeout. The possibilities are endless.

I feel like MSW is a good use case when you're adding full pages to Storybook. Usually, when you're at the level of a page, there are too many smart components down the component tree, and it's very difficult to deal with this situation differently. MSW allows us to manipulate scenarios for high-level components such as pages, which would be very hard to do otherwise.

What I really like about MSW is that once you've set up the mocks, you can reuse them on Storybook, unit tests, end-to-end tests, and even development. MSW can also mock GraphQL requests!

Installing the addon#

Let's go through the process of using MSW in MealDrop. Thankfully, there is a Storybook addon that takes care of the configuration for us: msw-storybook-addon. Let's add it to our project:

  1. Install the dependencies:

  1. Generate the service worker file in the public folder. Run the following command in the root of the project:

  1. Make sure that the generated mock service worker is available in Storybook. For that, we need to serve the public folder so the assets are available in Storybook. To do that, we need to add a staticDirs property in our .storybook/main.ts file, listing the folders we want to serve:

 

This page is a preview of Storybook for React Apps

Start a new discussion. All notification go to the author.