udacity / cloudflare-typescript-workers

Types and mocks for building a tested Typescript Cloudflare Worker, generates three NPM packages
Apache License 2.0
139 stars 12 forks source link

Cloning a response with new Response(response.body, response) discards headers #18

Open wuservices opened 4 years ago

wuservices commented 4 years ago

I have some test code that sets up a mock response like this:

fetchMock.mockResponse('', {
  headers: {
    'Content-Type': 'text/html'
  },
  status: 404
})

However, I noticed that my tests that were inspecting the Content-Type response header weren't behaving as expected. While debugging, I noticed that after I cloned the Response object with new Response(response.body, response), the resulting object did not have the response header. This seems to be the recommended way to clone the Response so that headers can be mutated, but I'm wondering if there's a way to get the test to behave the same way as Cloudflare does (keeping the headers in this circumstance).

Here's how you can see the issue in action if you run this code within a test:

const originalResponse = new Response('', {
  headers: {
    TestKey: 'TestValue'
  }
})
console.log('original', originalResponse.headers.get('TestKey'))

const clonedResponse = new Response(originalResponse.body, originalResponse)
console.log('cloned', clonedResponse.headers.get('TestKey'))

One possible workaround is to add code that does response.clone() when running a test instead of new Response(response.body, response), but that's not idea since it clutters the actual code. You can't use response.clone() in production because you still can't mutate the headers of the cloned Response object when you run the code in a real Cloudflare Worker.

Is there any way to get the test to behave more like Cloudflare Workers does?