Mock Service Worker relies heavily on the standard Fetch API classes like Request and Response when describing the network. But sometimes standards aren't enough. For example, you cannot mock a response cookie because JavaScript prohibits setting the "Set-Cookie" header on a Response instance. Learn how to side-step this limitation by using a new "HttpResponse" class from MSW.
Lecturer: [0:05] Go to the handlers file and input an HTTP response class from MSW. We will use this class to replace the native responses in our request handlers.
[0:10] The HTTP response class is a drop-in replacement for the Fetch API response. In fact, it extends it to always remain fully compatible. I recommend using the HTTP response class instead of the native response in your handlers.
[0:24] It provides extra capabilities to describe the network that would otherwise be unevaluable, like mocking the Set-Cookie response header which cannot be set on a regular response instance. Additionally, HTTP response comes with a set of built-in static methods to help define different mock responses.
[0:41] We will rewrite this JSON response using the JSON method on the HTTP response class. Notice that this is a static method, so we don't need the new keyword anymore.
[0:52] We can then drop converting the response body to a string because the JSON method will handle it for us and remove the Content-Type and Content-Length headers because they will be set automatically based on the JSON body that we provide.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!