Skip to content

Commit

Permalink
fix(mock): matching the complete header list when using fetch (nodejs…
Browse files Browse the repository at this point in the history
  • Loading branch information
panva authored and crysmags committed Feb 27, 2024
1 parent 42b7a04 commit e3dab86
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/mock/mock-utils.js
Expand Up @@ -33,6 +33,14 @@ function lowerCaseEntries (headers) {

function matchHeaders (mockDispatch, headers) {
if (typeof mockDispatch.headers === 'function') {
if (Array.isArray(headers)) { // fetch HeadersList
const clone = headers.slice()
const entries = []
for (let index = 0; index < clone.length; index += 2) {
entries.push([clone[index], clone[index + 1]])
}
headers = Object.fromEntries(entries)
}
return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
}
if (typeof mockDispatch.headers === 'undefined') {
Expand Down
27 changes: 27 additions & 0 deletions test/node-fetch/mock.js
Expand Up @@ -83,4 +83,31 @@ describe('node-fetch with MockAgent', () => {
expect(res.status).to.equal(200)
expect(await res.json()).to.deep.equal({ success: true })
})

it('should match the headers with a matching function', async () => {
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')

mockPool
.intercept({
path: '/test',
method: 'GET',
headers (headers) {
expect(headers).to.be.an('object')
expect(headers).to.have.property('user-agent', 'undici')
return true
}
})
.reply(200, { success: true })
.persist()

const res = await fetch('http://localhost:3000/test', {
method: 'GET',
headers: new Headers({ 'User-Agent': 'undici' })
})

expect(res.status).to.equal(200)
expect(await res.json()).to.deep.equal({ success: true })
})
})

0 comments on commit e3dab86

Please sign in to comment.