Skip to content

Commit

Permalink
Ensure Response isn't constructed w/ body when body should be null
Browse files Browse the repository at this point in the history
  • Loading branch information
zephraph committed Nov 3, 2023
1 parent 1d33318 commit 7a930f2
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions mockServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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
}

0 comments on commit 7a930f2

Please sign in to comment.