Intercept and Mock Server-Side HTTP Requests in MSW

Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

To control what happens to requests in Mock Service Worker, you need to intercept them first. Write your first request handler and learn how to intercept a server-side request our application makes in Remix's loader. And mocking a response? Using a Fetch API Response instance, of course!

Instructor: [0:00] On our home page, we have a loader function that tells Remix to make a server-side request to fetch the list of featured movies, but when we go to that page, we can see a request error because we're trying to make a request against the API that doesn't exist. Let's change that with MSW.

[0:15] Go to the handlers module and import { http } from 'msw'. We will use the http object to intercept http requests. Then in the list of handlers, type http, and take a look at the methods on this object. They represent http request methods. We will choose get because we're making a get request on the server, and call that method.

[0:37] As the first argument, we need to provide the request URL we wish to intercept. I will copy it directly from the remix loader. Then as the second argument, provide a callback function that will be called whenever this request happens. For now, let's print a console message in reaction to this request.

[0:55] We have just written a request handler. It's a function that controls the network and consists of two parts, a predicate that describes which requests to intercept, and a response resolver, a function that tells MSW how to handle this request.

[1:10] Let's verify that our request handler is working. Since the request we want to intercept happens on the server, we should be looking for this console message in the server logs in our Terminal.

[1:20] Once we refresh the page, we can see the Remix server printing our message, but the FetchError still remains because we haven't handled this request in any way just yet. To respond to an intercepted request, return a new Fetch API response instance from the Response resolver.

[1:37] In this case, our application expects a JSON response with the list of movies. I'm going to copy them right there, and I'm going to provide a Content-Type response header to specify that we're returning a JSON response. Save the changes, and refresh the page.

[1:55] What happens now is that our server makes a request, and MSW intercepts it and tries to find any matching request handlers for it. When it does, it executes the Response resolver function and uses any response it returns as the actual response our application receives.

~ 10 months ago

Where can I find the JSON string for the data?

Artem Zakharchenko
Artem Zakharchenkoinstructor
~ 10 months ago

Hi. You can find all the materials, including the JSON I used for mock data, on GitHub: https://github.com/kettanaito/movie-app. Checkout the "completed" branch to switch to the final state of the application, which will include the JSON you're looking for.

Let me know if you have any other questions!

Juan Marco
Juan Marco
~ 6 months ago

Here's the movies list if anybody is wondering:

const movies = [
  {
    id: '8061539f-f0d6-4187-843f-a25aadf948eb',
    slug: 'the-shawshank-redemption',
    title: 'The Shawshank Redemption',
    category: 'Drama',
    releasedAt: new Date('1994-10-14'),
    description:
      'Over the course of several years, two convicts form a friendship, seeking consolation and, eventually, redemption through basic compassion.',
    imageUrl:
      'https://m.media-amazon.com/images/M/MV5BNDE3ODcxYzMtY2YzZC00NmNlLWJiNDMtZDViZWM2MzIxZDYwXkEyXkFqcGdeQXVyNjAwNDUxODI@._V1_FMjpg_UX1200_.jpg',
  },
  {
    id: '3342a4f2-144b-4cef-8041-676affedfbb8',
    slug: 'the-godfather',
    title: 'The Godfather',
    category: 'Drama',
    releasedAt: new Date('1972-03-24'),
    description:
      'Don Vito Corleone, head of a mafia family, decides to hand over his empire to his youngest son Michael. However, his decision unintentionally puts the lives of his loved ones in grave danger.',
    imageUrl:
      'https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_FMjpg_UY1982_.jpg',
    reviews,
  },
  {
    id: 'b2b7e2d9-8b2e-4b7a-9b8a-7f9a0d7f7e0e',
    title: 'The Dark Knight',
    slug: 'the-dark-knight',
    category: 'Action',
    releasedAt: new Date('2008-07-18'),
    description:
      'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.',
    imageUrl:
      'https://m.media-amazon.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_FMjpg_UY2048_.jpg',
  },
]
Juan Marco
Juan Marco
~ 6 months ago

Note: Remove the reviews key so it works properly.

Markdown supported.
Become a member to join the discussionEnroll Today