ctx.fetch() not keeping original headers
See original GitHub issueDescribe the bug
When mocking a REST API using rest.get
i have a request containing headers, specifically “Authorization” header, and when i call ctx.fetch()
with this request, in order to get the original response, i have an unauthorized response.
This is due to the fact that my “Authorization” header is missing.
After taking a look at src/context/fetch.ts
, specifically the augmentRequestInit()
function, it seems that the type of my request headers is Headers
, and not string[][]
nor Record<string, string>
(see HeadersInit
type).
I think that the spread operator is not working for the type Headers
, therefore the headers are not kept :
const augmentRequestInit = (requestInit: RequestInit): RequestInit => {
return {
...requestInit,
headers: {
...requestInit.headers,
'x-msw-bypass': 'true',
},
}
}
Environment
-
msw: 0.15.5
-
nodejs: 12.16.1
-
npm: 6.13.4
-
browser version: Chrome
81.0.4044.129
To Reproduce
Steps to reproduce the behavior:
- make a request with “Authorization” header in an authent context
- call
ctx.fetch()
function with the original request - you will see an “401 Unauthorized (from ServiceWorker)” request in your network
My mock :
rest.get('/path/to/my/resource', async (req, res, ctx) => {
const mockedResponse = [
"Val 1",
"Val 2",
"Val 3"
];
const originalResponse = await ctx.fetch(req)
return res(
ctx.status(200),
ctx.json(originalResponse && originalResponse.length ? originalResponse : mockedResponse)
);
})
Expected behavior
Headers are kept.
Temporary Solution
I implemented my own fetch()
duplicating the existing one, and i change the implementation of the augmentRequestInit()
function.
My working version :
const augmentRequestInit = (requestInit: RequestInit): RequestInit => {
const headersCopy: Record<string, string> = {}
if (requestInit.headers instanceof Headers) {
requestInit.headers.forEach((value: string, name: string) => {
headersCopy[name] = value
});
}
// TODO handle the other types : string[][] and Record<string, string>
return {
...requestInit,
headers: {
...headersCopy,
'x-msw-bypass': 'true',
},
}
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:6 (5 by maintainers)
Top GitHub Comments
Yeah, that sounds great!
Big thanks to @juhanakristian for providing a fix on this.
The fix is published in
0.15.8
. Could you please update and let me know that it functions as expected? The workaround you’ve introduced should no longer be needed, original request headers must be proxied viactx.fetch()
. Thanks.