Intercept and Mock Client-Side HTTP Requests in MSW

Share this video with your friends

Social Share Links

Send Tweet

Request handlers you write in Mock Service Worker apply for both Node.js and the browser simultaneously. In this lesson, you will handle a client-side request for movie recommendations using the same http namespace you already know. We will also take a sneak peek at the browser's Network to see what happens to the requests when we mock them.

Lecturer: [0:00] let's render a list of recommended movies for each movie we are browsing. Since it's non-blocking information, we will perform this request on the client. In this case, it's a GET request to the api/recommendations root we've defined in Remix.

[0:16] We don't know how this route will be implemented just yet, but that doesn't stop us from developing and testing this UI. In our handlers module, let's add a new request handler for the recommendations endpoint.

[0:34] Notice that we don't have to provide the absolute request URL because this endpoint is served by our application. We can drop the application's host altogether and let MSW resolve the relative URL against the current location automatically. As a response, let's send back the first two movies we have in our movies collection.

[0:55] Pay attention to how we don't mention the environment or even the request client when defining our handlers. None of that is relevant because the network description should remain consistent no matter how or where a request is being sent.

[1:11] Save the changes and see the bottom of this page shining with recommended movies. Take a look at the network tab. Although we are clearly receiving the mock data right now, we can still see the actual request being sent, observe its properties, and check the response as we would do with a regular request because when using MSW, it remains a regular request.

[1:33] It gets intercepted on the network level using the service worker we registered earlier, which is indicated next to the response status code. This means our application actually performs the request as it would in production, and receives an actual response as if there is no mocking involved...