diff --git a/lib/mock/mock-agent.js b/lib/mock/mock-agent.js index 19bb01c2661..3079b15ec8c 100644 --- a/lib/mock/mock-agent.js +++ b/lib/mock/mock-agent.js @@ -17,7 +17,8 @@ const { kMockAgentAddCallHistoryLog, kMockAgentMockCallHistoryInstance, kMockAgentAcceptsNonStandardSearchParameters, - kMockCallHistoryAddLog + kMockCallHistoryAddLog, + kIgnoreTrailingSlash } = require('./mock-symbols') const MockClient = require('./mock-client') const MockPool = require('./mock-pool') @@ -37,6 +38,7 @@ class MockAgent extends Dispatcher { this[kIsMockActive] = true this[kMockAgentIsCallHistoryEnabled] = mockOptions?.enableCallHistory ?? false this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions?.acceptNonStandardSearchParameters ?? false + this[kIgnoreTrailingSlash] = mockOptions?.ignoreTrailingSlash ?? false // Instantiate Agent and encapsulate if (opts?.agent && typeof opts.agent.dispatch !== 'function') { @@ -54,11 +56,15 @@ class MockAgent extends Dispatcher { } get (origin) { - let dispatcher = this[kMockAgentGet](origin) + const originKey = this[kIgnoreTrailingSlash] + ? origin.replace(/\/$/, '') + : origin + + let dispatcher = this[kMockAgentGet](originKey) if (!dispatcher) { - dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) + dispatcher = this[kFactory](originKey) + this[kMockAgentSet](originKey, dispatcher) } return dispatcher } diff --git a/test/jest/mock-agent.test.js b/test/jest/mock-agent.test.js index 8463fce1ea0..4fc1139b35e 100644 --- a/test/jest/mock-agent.test.js +++ b/test/jest/mock-agent.test.js @@ -44,3 +44,26 @@ describe('MockAgent', () => { expect(jsonResponse).toEqual({ foo: 'bar' }) }) }) + +describe('MockAgent with ignoreTrailingSlash option', () => { + const trailingSlashUrl = 'http://localhost:9999/' + const noTrailingSlashUrl = 'http://localhost:9999' + + it('should not remove trailing slash from origin if the option is not enable', async () => { + const mockClient = new MockAgent() + + const dispatcherOne = mockClient.get(trailingSlashUrl) + const dispatcherTwo = mockClient.get(noTrailingSlashUrl) + + expect(dispatcherOne).not.toBe(dispatcherTwo) + }) + + it('should remove trailing slash from origin if enabled the option', async () => { + const mockClient = new MockAgent({ ignoreTrailingSlash: true }) + + const dispatcherOne = mockClient.get(trailingSlashUrl) + const dispatcherTwo = mockClient.get(noTrailingSlashUrl) + + expect(dispatcherOne).toBe(dispatcherTwo) + }) +})