Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Headers): forEach #1425

Merged
merged 2 commits into from May 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 10 additions & 12 deletions lib/fetch/headers.js
Expand Up @@ -354,26 +354,24 @@ class Headers {
return makeHeadersIterator(this[kHeadersSortedMap])
}

forEach (...args) {
/**
* @param {(value: string, key: string, self: Headers) => void} callbackFn
* @param {unknown} thisArg
*/
forEach (callbackFn, thisArg = globalThis) {
if (!(this instanceof Headers)) {
throw new TypeError('Illegal invocation')
}
if (args.length < 1) {
throw new TypeError(
`Failed to execute 'forEach' on 'Headers': 1 argument required, but only ${args.length} present.`
)
}
if (typeof args[0] !== 'function') {

if (typeof callbackFn !== 'function') {
throw new TypeError(
"Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
)
}
const callback = args[0]
const thisArg = args[1]

this[kHeadersSortedMap].forEach((value, index) => {
callback.apply(thisArg, [value, index, this])
})
for (const [key, value] of this) {
callbackFn.apply(thisArg, [value, key, this])
}
}

[Symbol.for('nodejs.util.inspect.custom')] () {
Expand Down
35 changes: 35 additions & 0 deletions test/fetch/headers.js
Expand Up @@ -289,6 +289,41 @@ tap.test('Headers set', t => {
})
})

tap.test('Headers forEach', t => {
const headers = new Headers([['a', 'b'], ['c', 'd']])

t.test('standard', t => {
t.equal(typeof headers.forEach, 'function')

headers.forEach((value, key, headerInstance) => {
t.ok(value === 'b' || value === 'd')
t.ok(key === 'a' || key === 'c')
t.equal(headers, headerInstance)
})

t.end()
})

t.test('when no thisArg is set, it is globalThis', (t) => {
headers.forEach(function () {
t.equal(this, globalThis)
})

t.end()
})

t.test('with thisArg', t => {
const thisArg = { a: Math.random() }
headers.forEach(function () {
t.equal(this, thisArg)
}, thisArg)

t.end()
})

t.end()
})

tap.test('Headers as Iterable', t => {
t.plan(8)

Expand Down