This video is available to students only

Adding the Restaurant detail page - mocking different 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:

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.


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:

This results in the following example:


This page is a preview of Storybook for React Apps

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