Improve Header's forEach method compliance with browser implementation. (#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).
This commit is contained in:
Leonardo Quixada 2021-01-25 19:59:55 -05:00 committed by GitHub
parent e333578417
commit 6ee9d3186f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 2 deletions

View File

@ -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]);
}
}

View File

@ -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');
}

View File

@ -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'],