Add a Single Source of Truth for Fixtures in MSW

Share this video with your friends

Social Share Links

Send Tweet

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.