Skip to content

Commit

Permalink
Fix headers construction in old browsers (#270)
Browse files Browse the repository at this point in the history
* Fix headers construction in old browsers

* Add headers test
  • Loading branch information
sholladay committed Jul 16, 2020
1 parent f67304e commit 71a8d59
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ const supportsStreams = typeof globals.ReadableStream === 'function';
const supportsFormData = typeof globals.FormData === 'function';

const mergeHeaders = (source1, source2) => {
const result = new globals.Headers(source1);
const result = new globals.Headers(source1 || {});
const isHeadersInstance = source2 instanceof globals.Headers;
const source = new globals.Headers(source2);
const source = new globals.Headers(source2 || {});

for (const [key, value] of source) {
if ((isHeadersInstance && value === 'undefined') || value === undefined) {
Expand Down
27 changes: 27 additions & 0 deletions test/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,33 @@ const echoHeaders = (request, response) => {
response.end(JSON.stringify(request.headers));
};

test.serial('works with nullish headers even in old browsers', async t => {
t.plan(4);

const server = await createTestServer();
server.get('/', echoHeaders);

const OriginalHeaders = Headers;
// Some old browsers throw for new Headers(undefined) or new Headers(null)
// so we check that Ky never does that and passes an empty object instead.
// See: https://github.com/sindresorhus/ky/issues/260
global.Headers = class Headers extends OriginalHeaders {
constructor(headersInit) {
t.deepEqual(headersInit, {});
super(headersInit);
}
};

const response = await ky.get(server.url).json();

t.is(typeof response, 'object');
t.truthy(response);

await server.close();

global.Headers = OriginalHeaders;
});

test('`user-agent`', async t => {
const server = await createTestServer();
server.get('/', echoHeaders);
Expand Down

0 comments on commit 71a8d59

Please sign in to comment.