From 7a930f20f0861f3f9abffc633010d1512b211b23 Mon Sep 17 00:00:00 2001 From: Justin Bennett Date: Fri, 3 Nov 2023 13:48:35 -0400 Subject: [PATCH] Ensure Response isn't constructed w/ body when body should be null --- mockServiceWorker.js | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/mockServiceWorker.js b/mockServiceWorker.js index 6498967c0..325dce2dd 100644 --- a/mockServiceWorker.js +++ b/mockServiceWorker.js @@ -125,7 +125,7 @@ async function handleRequest(event, requestId) { // always be a ReadableStream, even for 204 responses. // But when creating a new Response instance on the client, // the body for a 204 response must be null. - const responseBody = response.status === 204 ? null : responseClone.body + const responseBody = getSafeBody(response.status, responseClone.body) sendToClient( client, @@ -281,7 +281,7 @@ async function respondWithMock(response) { return Response.error() } - const mockedResponse = new Response(response.body, response) + const mockedResponse = new Response(getSafeBody(response.status, response.body), response) Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, { value: true, @@ -290,3 +290,23 @@ async function respondWithMock(response) { return mockedResponse } + +/** + * Ensures that the response body is only included when the status code doesn't indicate + * the body should be empty + * + * This is a workaround required due to a bug in MSW's implementation. Once fixed this file + * should be regenerated. + * + * @see https://github.com/mswjs/msw/issues/1827 + * + * @param {number} status + * @param {B} body + * @returns {B | null} + */ +function getSafeBody(status, body) { + if (status === 101 || status=== 103 || status === 204 || status === 205 || status === 304) { + return null + } + return body +} \ No newline at end of file