Unable to enableNetConnect
for localhost (127.0.0.1)
#1661
-
I’ve set up a mock agent to intercept requests to Given I don’t want to mock these requests, I have passed import { MockAgent, setGlobalDispatcher } from "undici";
const agent = new MockAgent();
agent.disableNetConnect();
agent.enableNetConnect("127.0.0.1");
export const githubAgent = () => {
const client = agent.get("https://api.github.com");
client.intercept({
path: "/repos/user/repo/contents/foo.txt",
method: "PUT"
}).reply(201, {
content: { path: "foo.txt" },
commit: { message: "Message" },
}).times(3);
return client;
};
setGlobalDispatcher(githubAgent()); However, when running my tests, all paths are intercepted. For example, I need to call both
Full error stackTypeError: fetch failed
at Object.processResponse (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:199:23)
at /Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:928:38
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: MockNotMatchedError: Mock dispatch not matched for path '/micropub': subsequent request to origin https://api.github.com was not allowed (net.connect is not enabled for this origin)
at MockPool.dispatch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/mock/mock-utils.js:362:19)
at /Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:1906:79
at new Promise (<anonymous>)
at dispatch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:1906:12)
at httpNetworkFetch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:1718:61)
at httpNetworkOrCacheFetch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:1423:35)
at httpFetch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:1011:39)
at schemeFetch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:875:20)
at /Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:570:22
at mainFetch (/Users/paulrobertlloyd/Sites/indiekit/node_modules/undici/lib/fetch/index.js:620:7) {
code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
} Have I set up the mock agent incorrectly, or is this a bug? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Turns out agent.enableNetConnect(/(?:127\.0\.0\.1:\d{5})/); |
Beta Was this translation helpful? Give feedback.
Turns out
enableNetConnect
looks for an exact match for a given host, and doesn’t ignore the port. As a port is randomly assigned in each test, I used a regex instead: