Documentation Index
Fetch the complete documentation index at: https://mintlify.com/nodejs/undici/llms.txt
Use this file to discover all available pages before exploring further.
MockAgent is the primary entry point for HTTP mocking in undici. It extends Dispatcher and wraps a real Agent, intercepting requests before they hit the network so your tests never depend on external services. When set as the global dispatcher, every request() or fetch() call in your process routes through the mock layer automatically.
Constructor
Instantiating MockAgent
Options passed to the underlying
Agent. All AgentOptions are supported in addition to the following.Activation
Setting as the global dispatcher
The most common pattern is to installMockAgent as the global dispatcher so all requests in the process go through it:
Global MockAgent setup
mockAgent.get(origin)
Returns the MockPool (or MockClient when connections === 1) for the given origin, creating it if it does not already exist. This is the object on which you register interceptors.
The origin to retrieve or create a mock dispatcher for.
| Matcher type | Condition to pass |
|---|---|
string | Exact match |
RegExp | Regex must pass |
Function | Must return true |
Returns
MockClient when connections === 1, otherwise MockPool.Getting a MockPool for an origin
Origin matching with RegExp
Origin matching with a function
mockAgent.activate() / mockAgent.deactivate()
MockAgent is active by default. Call deactivate() to disable mocking temporarily and activate() to re-enable it.
Temporarily disabling mocks
Interceptors
Interceptors define the rules for matching requests and the responses to return. You register them on aMockPool or MockClient obtained from mockAgent.get().
mockPool.intercept(options)
Returns a MockInterceptor that you chain to define the response.
A
MockInterceptor instance. Chain the methods below to define the response.mockInterceptor.reply(statusCode, body, options?)
Defines the response returned when the interceptor matches.
HTTP status code for the mocked response.
Response body. Objects are serialized as JSON. Strings and buffers are sent as-is. Pass a callback to compute the body dynamically from the incoming request — the callback receives
{ method, url, body, headers, origin }.mockInterceptor.reply(callback)
Alternative signature — pass a single callback that returns the full reply options:
Reply with a full options callback
mockInterceptor.replyWithError(error)
Causes the matched request to throw the given error.
Simulating a network error
mockInterceptor.defaultReplyHeaders(headers)
Sets headers that are merged into every subsequent reply() on this interceptor.
Default response headers.
mockInterceptor.defaultReplyTrailers(trailers)
Sets trailers that are merged into every subsequent reply() on this interceptor.
Default response trailers.
mockInterceptor.replyContentLength()
Automatically calculates and includes a content-length header in the response.
MockScope — controlling repeat behaviour
reply(), replyWithError(), and the other reply methods return a MockScope. Use the following methods to control how many times the interceptor fires:
The interceptor matches indefinitely. Without this, each interceptor matches once by default.
The interceptor matches exactly
n times. Overridden by persist().Delays the reply by
ms milliseconds.Matcher types
Allpath, method, body, and individual header values accept three matcher types:
| Type | Behaviour |
|---|---|
string | Exact equality check |
RegExp | regex.test(value) must be true |
Function | Function must return true |
Mixed matchers on an interceptor
Network control
mockAgent.disableNetConnect()
Causes any request that does not match a registered interceptor to throw a MockNotMatchedError. Use this in tests to ensure every network call is explicitly mocked.
Disabling real network access
mockAgent.enableNetConnect(host?)
Allows unmatched requests to reach the real network, optionally restricted to specific hosts. Calling this without arguments allows all real requests.
When provided, only requests matching this host are allowed through. When omitted, all requests are permitted. Call multiple times to allow multiple hosts.
Allowing specific hosts to bypass mocking
Assertions
mockAgent.assertNoPendingInterceptors(options?)
Throws an UndiciError if any registered interceptors have not been fully consumed. An interceptor is pending when it was registered but:
- has not been invoked at all (single-use default), or
- is persistent (
.persist()) but was never called, or - has fewer invocations remaining than
times(n)requires.
Asserting all interceptors were consumed
mockAgent.pendingInterceptors()
Returns an array of all pending interceptors without throwing. Each entry is a MockDispatch augmented with an origin field.
Call history
Call history must be enabled either at construction time viaenableCallHistory: true or by calling mockAgent.enableCallHistory() afterwards.
Enabling history
Enabling call history at construction
Enabling call history after construction
mockAgent.getCallHistory()
Returns the MockCallHistory instance, or undefined if history was never enabled.
MockCallHistory methods
Returns all recorded call logs as an array.
Returns the first recorded call.
Returns the most recent recorded call.
Returns the nth call (1-indexed). Throws if
n is not a positive integer.Filters recorded calls.
criteria can be a function, RegExp, or an object with MockCallHistoryLog property keys. The optional options.operator is 'OR' (default) or 'AND'.Filters by
path. Accepts a string or RegExp.Filters by HTTP method. Accepts a string or
RegExp.Filters by origin. Accepts a string or
RegExp.Filters by the full URL including query string and hash. Accepts a string or
RegExp.Clears all recorded logs. Called automatically by
mockAgent.close().MockCallHistoryLog properties
Each log entry exposes the following properties:
HTTP method of the request.
Protocol and host, e.g.
'http://example.com'.Path portion of the URL, always starting with
/.Complete URL including protocol, host, path, query, and hash.
Parsed query parameters as a plain object.
Request headers.
Request body.
Protocol string, e.g.
'http:'.Host and port, e.g.
'example.com:3000'.Port number as a string, or an empty string if absent.
URL hash including
#, or an empty string if absent.Clearing call history
Clearing all recorded calls
Errors
MockNotMatchedError
Thrown when disableNetConnect() is active and a request does not match any registered interceptor.
Importing MockNotMatchedError
Cleanup
CallmockAgent.close() after tests complete. This clears call history and closes all underlying mock pools and clients.
Closing MockAgent after tests
Complete example
The following example usesnode:test to verify a JSON API endpoint end-to-end with no real network traffic:
Full test with MockAgent and node:test