Use the HttpResponse Class in MSW

Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

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.