Skip to content

Commit

Permalink
Improve Header's forEach method compliance with browser implementatio…
Browse files Browse the repository at this point in the history
…n. (#1074)

* Improve Header's forEach method compliance with browser implementation.

* Replaced callback.call with Reflect.apply on Headers' forEach.

* Set undefined as default value for Header' forEach second argument.

* Rewrote test case where 'this' is undefined.

* Ignored lint issues (no-eq-null and eqeqeq).
  • Loading branch information
lquixada committed Jan 26, 2021
1 parent e333578 commit 6ee9d31
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ export default class Headers extends URLSearchParams {
return value;
}

forEach(callback) {
forEach(callback, thisArg = undefined) {
for (const name of this.keys()) {
callback(this.get(name), name);
Reflect.apply(callback, thisArg, [this.get(name), name, this]);
}
}

Expand Down
1 change: 1 addition & 0 deletions src/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export default class Request extends Body {
signal = init.signal;
}

// eslint-disable-next-line no-eq-null, eqeqeq
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');
}
Expand Down
31 changes: 31 additions & 0 deletions test/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,37 @@ describe('Headers', () => {
]);
});

it('should be iterable with forEach', () => {
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Accept', 'text/plain');
headers.append('Content-Type', 'text/html');

const results = [];
headers.forEach((value, key, object) => {
results.push({value, key, object});
});

expect(results.length).to.equal(2);
expect({key: 'accept', value: 'application/json, text/plain', object: headers}).to.deep.equal(results[0]);
expect({key: 'content-type', value: 'text/html', object: headers}).to.deep.equal(results[1]);
});

it('should set "this" to undefined by default on forEach', () => {
const headers = new Headers({Accept: 'application/json'});
headers.forEach(function () {
expect(this).to.be.undefined;
});
});

it('should accept thisArg as a second argument for forEach', () => {
const headers = new Headers({Accept: 'application/json'});
const thisArg = {};
headers.forEach(function () {
expect(this).to.equal(thisArg);
}, thisArg);
});

it('should allow iterating through all headers with for-of loop', () => {
const headers = new Headers([
['b', '2'],
Expand Down

0 comments on commit 6ee9d31

Please sign in to comment.