How to Mock Storybook App Loading Scenarios With MSW
Let's mock the API scenarios with MSW.
Data fetching#
We have tackled most of the configuration required to render the RestaurantDetailPage
component. What is left to do is proxy the server requests with MSW so that we don't make calls to the real backend, and manipulate the response so that we can force different scenarios of our page. The installation steps and basic usage were already covered in the Data Fetching: Mocking Requests lesson, so make sure to check it out if you've missed it.
Let's first recap and identify the states of our page, which are:
Success: The page renders correctly with the restaurant information (already covered in the previous lesson)
Loading: While the page is loading, a spinner is presented
Error - Not found: If the server responds with a status 404, the "not found" screen is presented
Error - Server error: If the server responds with a status 500, the "error" screen is presented

The next step is to identify which request we are trying to mock. The component fetches data using a URL that comes from a constant in src/api/index.ts
:
xxxxxxxxxx
export const BASE_URL = 'https://mealdrop.netlify.app/.netlify/functions/restaurants'
Given that info, essentially, we need to use MSW to listen to that URL and add different handlers per story so that we can reproduce every one of the scenarios for our page.
Defining the scenarios#
Let's open the src/pages/RestaurantDetailPage/RestaurantDetailPage.stories.tsx
file and start defining the scenarios. MSW will help us to easily define each one.
Success#
The first scenario we should implement is the default, where the API request successfully returns data. We then use the mock data from the stubs in the MSW handler:
xxxxxxxxxx
// src/pages/RestaurantDetailPage/RestaurantDetailPage.stories.tsx
// ...other imports
import { rest } from 'msw'
import { BASE_URL } from '../../api'
import { restaurants } from '../../stub/restaurants'
// ...rest of the code
Success.parameters = {
design: {
type: 'figma',
url: 'https://www.figma.com/proto/3Q1HTCalD0lJnNvcMoEw1x/Mealdrop?node-id=169%3A510&scaling=scale-down-width&page-id=135%3A257&starting-point-node-id=135%3A258',
},
msw: {
handlers: [
rest.get(BASE_URL, (req, res, ctx) => {
return res(ctx.json(restaurants[0]))
}),
],
},
}
This results in the following example:
This lesson preview is part of the Storybook for React Apps course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Storybook for React Apps, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
