diff --git a/lib/helpers/request.js b/lib/helpers/request.js index c433c7b3b..6a4c6d9b1 100644 --- a/lib/helpers/request.js +++ b/lib/helpers/request.js @@ -19,6 +19,7 @@ export default async function request(options) { signal = AbortSignal.timeout(2500), agent = options.url.protocol === 'http:' ? http.globalAgent : https.globalAgent, dnsLookup = dns.lookup, + 'user-agent': userAgent = undefined, } = instance(this).configuration('httpOptions')(new URL(options.url)); const helperOptions = pickBy({ signal, agent, dnsLookup }, Boolean); @@ -34,12 +35,12 @@ export default async function request(options) { throw new TypeError('"dnsLookup" http request option must be a function'); } - if (helperOptions['user-agent'] !== undefined && typeof helperOptions['user-agent'] !== 'string') { + if (userAgent !== undefined && typeof userAgent !== 'string') { throw new TypeError('"user-agent" http request option must be a string'); } // eslint-disable-next-line no-param-reassign - options.headers['user-agent'] = helperOptions['user-agent']; + options.headers['user-agent'] = userAgent; return got({ ...options, diff --git a/test/helpers/request/request.config.js b/test/helpers/request/request.config.js new file mode 100644 index 000000000..81bfca558 --- /dev/null +++ b/test/helpers/request/request.config.js @@ -0,0 +1,18 @@ +import merge from 'lodash/merge.js'; + +import getConfig from '../../default.config.js'; + +const config = getConfig(); +merge(config, { + httpOptions(url) { + if (url.pathname === '/with-custom-user-agent') { + return { 'user-agent': 'some user agent' }; + } + + return {}; + }, +}); + +export default { + config, +}; diff --git a/test/helpers/request/request.test.js b/test/helpers/request/request.test.js new file mode 100644 index 000000000..2eb8a542d --- /dev/null +++ b/test/helpers/request/request.test.js @@ -0,0 +1,39 @@ +import { expect } from 'chai'; +import nock from 'nock'; + +import bootstrap from '../../test_helper.js'; +import request from '../../../lib/helpers/request.js'; + +describe('request helper', () => { + before(bootstrap(import.meta.url)); + + afterEach(nock.cleanAll); + + afterEach(() => { + expect(nock.isDone()).to.be.true; + }); + + describe('when using custom httpOptions', () => { + it('defaults to not sending the user-agent HTTP header', async function () { + nock('https://www.example.com/', { + badheaders: ['user-agent'], + }) + .get('/') + .reply(200); + + await request.call(this.provider, { url: 'https://www.example.com' }); + }); + + it("uses a custom 'user-agent' HTTP header", async function () { + nock('https://www.example.com/', { + reqheaders: { + 'user-agent': 'some user agent', + }, + }) + .get('/with-custom-user-agent') + .reply(200); + + await request.call(this.provider, { url: 'https://www.example.com/with-custom-user-agent' }); + }); + }); +});