Add a Single Source of Truth for Fixtures in MSW

Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

As you add more request handlers in Mock Service Worker, introducing a source of truth for the static data can help reduce the clutter and keep the network description focus on behavior instead of repeating fixtures. In this lesson, we will refactor our code by moving the static data outside and reusing it across existing request handlers.

Lecturer: [0:00] Let's structure our mock data a little better by storing the list of all movies in a new variable called movies. Put it on the root level of the handlers module so any request handler would always have access to it. You can think of this variable as a mock database we will use during development.

[0:18] Next, let's update the featuredMovies handler to return the entire collection of movies, instead of a hard-coded JSON. In the movieDetail handler, we can drop these manual checks for the movie slug. Instead, let's use the find method on the movies array to look up any movie by the given slug path parameter.

[0:41] This makes our handler much more versatile, as it will now return any existing movie as long as it's present in the movies collection. By moving the static data outside of your request handlers, you allow them to focus on the actual network logic they describe, and also make them much easier to read and change and change.

Kushal Mahajan
Kushal Mahajan
~ a year ago

It would have been helpful to have movies stored somewhere in content folder. There is not reference to the API as well in this or previous two videos. I had to hardcode the movie :(

Artem Zakharchenko
Artem Zakharchenkoinstructor
~ a year ago

Hey, Kushal. You can store the static fixtures wherever you prefer. This is just an illustration of the concept that keeping them in a single place and then referencing them in different request handlers is beneficial to reduce repetition. You can even use libraries like Faker to generate content on runtime. Imagination is your only limit! Well, imagination and JavaScript ;)

Markdown supported.
Become a member to join the discussionEnroll Today