A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses.
new MockPool(origin, [options])
Arguments:
originstring - It should only include the protocol, hostname, and port.
optionsMockPoolOptions - It extends the Pool options.
Returns: MockPool
Parameter: MockPoolOptions
Extends: PoolOptions
agentAgent - the agent to associate this MockPool with.
Example - Basic MockPool instantiation
We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered.
This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. For example if you expect to make 2 requests inside a test, you need to call intercept() twice. Assuming you use disableNetConnect() you will get MockNotMatchedError on the second request when you only call intercept() once.
When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted.
Returns: MockInterceptor corresponding to the input options.
Parameter: MockPoolInterceptOptions
pathstring | RegExp | (path: string) => boolean - a matcher for the HTTP request path. When a RegExp or callback is used, it will match against the request path including all query parameters in alphabetical order. When a string is provided, the query parameters can be conveniently specified through the MockPoolInterceptOptions.query setting.
methodstring | RegExp | (method: string) => boolean - (optional) - a matcher for the HTTP request method. Defaults to GET.
bodystring | RegExp | (body: string) => boolean - (optional) - a matcher for the HTTP request body.
headersRecord<string, string | RegExp | (body: string) => boolean> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way.
queryRecord<string, any> | null - (optional) - a matcher for the HTTP request query string params. Only applies when a string was provided for MockPoolInterceptOptions.path.
ignoreTrailingSlashboolean - (optional) - set to true if the matcher should also match by ignoring potential trailing slashes in MockPoolInterceptOptions.path.
Return: MockInterceptor
We can define the behaviour of an intercepted request with the following options.
reply(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for responseOptions is {}.
reply(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data.
replyWithError(error: Error) => MockScope - define an error for a matching request to throw.
defaultReplyHeaders(headers: Record<string, string>) => MockInterceptor - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply.
defaultReplyTrailers(trailers: Record<string, string>) => MockInterceptor - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply.
replyContentLength() => MockInterceptor - define automatically calculated content-length headers to be included in subsequent replies.
The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is.
By default, reply and replyWithError define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned MockScope).
Parameter: MockResponseOptions
headersRecord<string, string> - headers to be included on the mocked reply.
trailersRecord<string, string> - trailers to be included on the mocked reply.
Return: MockScope
A MockScope is associated with a single MockInterceptor. With this, we can configure the default behaviour of an intercepted reply.
delay(waitInMs: number) => MockScope - delay the associated reply by a set amount in ms.
persist() => MockScope - any matching request will always reply with the defined response indefinitely.
times(repeatTimes: number) => MockScope - any matching request will reply with the defined response a fixed amount of times. This is overridden by persist.
Example - Basic Mocked Request
Example - Mocked request using reply data callbacks
Example - Mocked request using reply options callback
Example - Basic Mocked requests with multiple intercepts
Example - Mocked request with query body, request headers and response headers and trailers
Example - Mocked request using different matchers
Example - Mocked request with reply with a defined error
Example - Mocked request with defaultReplyHeaders
Example - Mocked request with defaultReplyTrailers
Example - Mocked request with automatic content-length calculation
Example - Mocked request with automatic content-length calculation on an object
Example - Mocked request with persist enabled
Example - Mocked request with times enabled
Example - Mocked request with path callback
MockPool.close()
Closes the mock pool and de-registers from associated MockAgent.
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET'
}).reply(200, 'foo').persist()
const result1 = await request('http://localhost:3000/foo')
// Will match and return mocked data
const result2 = await request('http://localhost:3000/foo')
// Will match and return mocked data
// Etc
import { MockAgent, setGlobalDispatcher, request } from 'undici'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET'
}).reply(200, 'foo').times(2)
const result1 = await request('http://localhost:3000/foo')
// Will match and return mocked data
const result2 = await request('http://localhost:3000/foo')
// Will match and return mocked data
const result3 = await request('http://localhost:3000/foo')
// Will not match and make attempt a real request
import { MockAgent, setGlobalDispatcher, request } from 'undici'
import querystring from 'querystring'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
const matchPath = requestPath => {
const [pathname, search] = requestPath.split('?')
const requestQuery = querystring.parse(search)
if (!pathname.startsWith('/foo')) {
return false
}
if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') {
return false
}
return true
}
mockPool.intercept({
path: matchPath,
method: 'GET'
}).reply(200, 'foo')
const result = await request('http://localhost:3000/foo?foo=bar')
// Will match and return mocked data
import { MockAgent } from 'undici'
const mockAgent = new MockAgent()
const mockPool = mockAgent.get('http://localhost:3000')
await mockPool.close()
import { MockAgent } from 'undici'
const mockAgent = new MockAgent()
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET',
}).reply(200, 'foo')
const {
statusCode,
body
} = await mockPool.request({
origin: 'http://localhost:3000',
path: '/foo',
method: 'GET'
})
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}