Skip to content

15.0.0-beta.4 Doesn't support undici requests with custom agent/dispatcher #2888

@lajohnston

Description

@lajohnston

Please avoid duplicates

Reproducible test case

(see post)

Nock Version

15.0.0-beta.4

Node Version

v22.17.0

TypeScript Version

No response

What happened?

Hi there,

It seems the partial Undici support is working for most requests in 15.0.0-beta.4 now 🎉

One limitation we've observed though is that if you pass in a dispatcher in the request options (or use undici.setGlobalDispatcher) it results in the request not being intercepted. A custom Agent is needed to add things like certs or adjust keepAlive settings.

import { Agent, fetch } from 'undici';

const agent = new Agent({
    keepAliveTimeout: 1000,
});

const response = await fetch('some url', {
    method: 'GET',
    dispatcher: agent,
});

Note, in this example we're importing the undici library rather than using native fetch, as it seems the latter doesn't export the Undici Agent and so cannot be customised.

It seems the given dispatcher bypasses or overrides the NockAgent that's set here:

function activate() {
undici.setGlobalDispatcher(new NockAgent())
}

Workaround

Use Reflect (or some other stubbing method) when initialising the test suite to ensure undici.Agent in the code returns the Nock stub.

const undici = require('undici');

Reflect.set(undici, 'Agent', function () {
    const nockAgent = undici.getGlobalDispatcher();
    return nockAgent;
});

Would you be interested in contributing a fix?

  • yes

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions