From e3dab86fc50965782cb287b4393796145839e780 Mon Sep 17 00:00:00 2001 From: Filip Skokan Date: Wed, 23 Mar 2022 15:46:15 +0100 Subject: [PATCH] fix(mock): matching the complete header list when using fetch (#1301) --- lib/mock/mock-utils.js | 8 ++++++++ test/node-fetch/mock.js | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/mock/mock-utils.js b/lib/mock/mock-utils.js index fc47bcd23a5..8bd4df51a09 100644 --- a/lib/mock/mock-utils.js +++ b/lib/mock/mock-utils.js @@ -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') { diff --git a/test/node-fetch/mock.js b/test/node-fetch/mock.js index 52eee8af543..d4881eabc35 100644 --- a/test/node-fetch/mock.js +++ b/test/node-fetch/mock.js @@ -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 }) + }) })