Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 50 additions & 15 deletions lib/mock/mock-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@ const {
kMockAgentAddCallHistoryLog,
kMockAgentMockCallHistoryInstance,
kMockAgentAcceptsNonStandardSearchParameters,
kMockCallHistoryAddLog
kMockCallHistoryAddLog,
kIgnoreTrailingSlash
} = require('./mock-symbols')
const MockClient = require('./mock-client')
const MockPool = require('./mock-pool')
const { matchValue, normalizeSearchParams, buildAndValidateMockOptions } = require('./mock-utils')
const {
matchValue,
normalizeSearchParams,
buildAndValidateMockOptions
} = require('./mock-utils')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There looks to be some formatting changes included in here. Is this actually from the formatter in the repo or something else?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be my editor. My neovim config includes auto-formatting with prettier and eslint.

const { InvalidArgumentError, UndiciError } = require('../core/errors')
const Dispatcher = require('../dispatcher/dispatcher')
const PendingInterceptorsFormatter = require('./pending-interceptors-formatter')
Expand All @@ -35,12 +40,17 @@ class MockAgent extends Dispatcher {

this[kNetConnect] = true
this[kIsMockActive] = true
this[kMockAgentIsCallHistoryEnabled] = mockOptions?.enableCallHistory ?? false
this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions?.acceptNonStandardSearchParameters ?? false
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') {
throw new InvalidArgumentError('Argument opts.agent must implement Agent')
throw new InvalidArgumentError(
'Argument opts.agent must implement Agent'
)
}
const agent = opts?.agent ? opts.agent : new Agent(opts)
this[kAgent] = agent
Expand All @@ -54,11 +64,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
}
Expand All @@ -69,13 +83,17 @@ class MockAgent extends Dispatcher {

this[kMockAgentAddCallHistoryLog](opts)

const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters]
const acceptNonStandardSearchParameters =
this[kMockAgentAcceptsNonStandardSearchParameters]

const dispatchOpts = { ...opts }

if (acceptNonStandardSearchParameters && dispatchOpts.path) {
const [path, searchParams] = dispatchOpts.path.split('?')
const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters)
const normalizedSearchParams = normalizeSearchParams(
searchParams,
acceptNonStandardSearchParameters
)
dispatchOpts.path = `${path}?${normalizedSearchParams}`
}

Expand All @@ -97,7 +115,11 @@ class MockAgent extends Dispatcher {
}

enableNetConnect (matcher) {
if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
if (
typeof matcher === 'string' ||
typeof matcher === 'function' ||
matcher instanceof RegExp
) {
if (Array.isArray(this[kNetConnect])) {
this[kNetConnect].push(matcher)
} else {
Expand All @@ -106,7 +128,9 @@ class MockAgent extends Dispatcher {
} else if (typeof matcher === 'undefined') {
this[kNetConnect] = true
} else {
throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
throw new InvalidArgumentError(
'Unsupported matcher. Must be one of String|Function|RegExp.'
)
}
}

Expand Down Expand Up @@ -185,7 +209,11 @@ class MockAgent extends Dispatcher {

// If we match, create a pool and assign the same dispatches
for (const [keyMatcher, result] of Array.from(this[kClients])) {
if (result && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
if (
result &&
typeof keyMatcher !== 'string' &&
matchValue(keyMatcher, origin)
) {
const dispatcher = this[kFactory](origin)
this[kMockAgentSet](origin, dispatcher)
dispatcher[kDispatches] = result.dispatcher[kDispatches]
Expand All @@ -202,11 +230,18 @@ class MockAgent extends Dispatcher {
const mockAgentClients = this[kClients]

return Array.from(mockAgentClients.entries())
.flatMap(([origin, result]) => result.dispatcher[kDispatches].map(dispatch => ({ ...dispatch, origin })))
.flatMap(([origin, result]) =>
result.dispatcher[kDispatches].map((dispatch) => ({
...dispatch,
origin
}))
)
.filter(({ pending }) => pending)
}

assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
assertNoPendingInterceptors ({
pendingInterceptorsFormatter = new PendingInterceptorsFormatter()
} = {}) {
const pending = this.pendingInterceptors()

if (pending.length === 0) {
Expand Down
64 changes: 48 additions & 16 deletions test/jest/mock-agent.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { getResponse } = require('../../lib/mock/mock-utils')

/* global describe, it, afterEach, expect */

describe('MockAgent', () => {
describe('smoking test in jest', () => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this should be renamed

let mockAgent

afterEach(() => {
Expand All @@ -21,21 +21,30 @@ describe('MockAgent', () => {
setGlobalDispatcher(mockAgent)
const mockClient = mockAgent.get(baseUrl)

mockClient.intercept({
path: '/foo?hello=there&see=ya',
method: 'POST',
body: 'form1=data1&form2=data2'
}).reply(200, { foo: 'bar' }, {
headers: {
'content-type': 'application/json'
},
trailers: { 'Content-MD5': 'test' }
})

const { statusCode, headers, trailers, body } = await request(`${baseUrl}/foo?hello=there&see=ya`, {
method: 'POST',
body: 'form1=data1&form2=data2'
})
mockClient
.intercept({
path: '/foo?hello=there&see=ya',
method: 'POST',
body: 'form1=data1&form2=data2'
})
.reply(
200,
{ foo: 'bar' },
{
headers: {
'content-type': 'application/json'
},
trailers: { 'Content-MD5': 'test' }
}
)

const { statusCode, headers, trailers, body } = await request(
`${baseUrl}/foo?hello=there&see=ya`,
{
method: 'POST',
body: 'form1=data1&form2=data2'
}
)
expect(statusCode).toBe(200)
expect(headers).toEqual({ 'content-type': 'application/json' })
expect(trailers).toEqual({ 'content-md5': 'test' })
Expand All @@ -44,3 +53,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)
})
})