示例
undici 8.10.0: Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net connect disabling in undici 8.10.0.
已验证示例 — npm undici 8.10.0: Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net connect disabling…
sha256:eabd61438b3ee2fb72c65dbb20868737ee47bc5e6f4020752114794f1179cc69
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 3
- 构建过它的签名密钥
- 3
声明的环境
node linux x64 node node npm
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-17 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-07 |
案例
HOW- 目标
- Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net connect disabling in undici 8.10.0.
- 符号
-
- MockAgent
- MockPool
- request
- setGlobalDispatcher
- 环境
- node
- 创建时间
- 2026-08-17T11:56:06Z
契约
- MockAgent intercepts requests by origin and consumes each registered interceptor exactly once by default, rejecting subsequent unintercepted requests with MockNotMatchedError when net connect is disabled.
- Interceptors configured with .times(n) or .persist() allow repeated matching before being exhausted.
- Dynamic reply callbacks in interceptors receive the incoming request options including method, path, headers, and body.
- assertNoPendingInterceptors verifies that all registered interceptors were dispatched, throwing an UndiciError if any interceptor remains pending.
文件
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
源代码
# undici 8.10.0 MockAgent Request Interception and Verification
## Prior Findings from Known Solution Search
A search for existing verified samples on `undici` returned two published samples:
- `sha256:58c13cc15f12e5f7e9c8dab8a50ff21446e25ffae7a78a5b505a95eae5b06e5e`: Retry fetch requests with bodies safely and avoid cross-realm TypeError between undici and global fetch.
- `sha256:a40d7f23a7553db846896ca28ec8f7c6c6b132e22d61c01c48414c25a4c841ca`: Dispatch Client and Pool requests composed with interceptors.dns() without origin TypeError in undici 8.4.1.
This sample addresses a distinct area of `undici`: proving the request interception, consumption semantics, dynamic callback handling, and pending interceptor assertions provided by `MockAgent`.
## Pinned Release
- `undici@8.10.0` pinned in `package.json` and `package-lock.json`.
## Observed Behaviour
1. **Origin Interception and Single Consumption**:
`MockAgent` intercepts outgoing HTTP requests by target origin (such as `http://example.com`). Each registered interceptor is consumed exactly once by default. When network connectivity is disabled via `mockAgent.disableNetConnect()`, any subsequent unmatched request immediately rejects with `MockNotMatchedError` (`UND_MOCK_ERR_MOCK_NOT_MATCHED`).
2. **Repeated Invocations with `.times(n)`**:
Interceptors configured with `.times(n)` (or `.persist()`) remain active for exactly `n` dispatches before becoming exhausted, at which point subsequent calls trigger `MockNotMatchedError`.
3. **Dynamic Reply Callbacks**:
The `.reply(statusCode, callback, options)` API passes the incoming dispatch options (`path`, `method`, `headers`, and `body`) to the callback function, allowing dynamic responses based on request payload and headers.
4. **Interceptor Assertions**:
`mockAgent.assertNoPendingInterceptors()` succeeds when all registered intercepts have been invoked, and throws an `UndiciError` (`UND_ERR`) with a table of pending interceptors if any defined intercept was never triggered.
{"case":{"caseId":"case:sha256:c65d0a1e55bb4141e039ed7589d63819a13cb8d84b0d7b5bdc22fa2cd1319283","contract":["MockAgent intercepts requests by origin and consumes each registered interceptor exactly once by default, rejecting subsequent unintercepted requests with MockNotMatchedError when net connect is disabled.","Interceptors configured with .times(n) or .persist() allow repeated matching before being exhausted.","Dynamic reply callbacks in interceptors receive the incoming request options including method, path, headers, and body.","assertNoPendingInterceptors verifies that all registered interceptors were dispatched, throwing an UndiciError if any interceptor remains pending."],"goal":"Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net connect disabling in undici 8.10.0.","kind":"HOW","packages":["pkg:npm/undici@8.10.0"],"schemaVersion":1,"symbols":["MockAgent","MockPool","request","setGlobalDispatcher"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/undici@8.10.0"],"schemaVersion":1,"symbols":["MockAgent","MockPool","request","setGlobalDispatcher"],"verifierAdapter":"node-typescript@1"}
{
"name": "npm-undici-version-depth",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npm-undici-version-depth",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"undici": "8.10.0"
}
},
"node_modules/undici": {
"version": "8.10.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-8.10.0.tgz",
"integrity": "sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==",
"license": "MIT",
"engines": {
"node": ">=22.19.0"
}
}
}
}
{
"name": "npm-undici-version-depth",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"undici": "8.10.0"
}
}
import assert from 'node:assert/strict';
import { MockAgent, setGlobalDispatcher, request } from 'undici';
async function main() {
const mockAgent = new MockAgent();
mockAgent.disableNetConnect();
setGlobalDispatcher(mockAgent);
const mockPool = mockAgent.get('http://example.com');
// 1. Single-use intercept and MockNotMatchedError when net connect is disabled
mockPool.intercept({
path: '/api/resource',
method: 'GET',
}).reply(200, { id: 1, name: 'resource-1' }, {
headers: { 'content-type': 'application/json' },
});
const res1 = await request('http://example.com/api/resource', { method: 'GET' });
assert.equal(res1.statusCode, 200);
const data1 = await res1.body.json();
assert.deepEqual(data1, { id: 1, name: 'resource-1' });
// Second invocation should fail because intercept was consumed once and net connect is disabled
await assert.rejects(
async () => request('http://example.com/api/resource', { method: 'GET' }),
(err) => {
assert.equal(err.name, 'MockNotMatchedError');
assert.equal(err.code, 'UND_MOCK_ERR_MOCK_NOT_MATCHED');
return true;
}
);
// 2. Interceptors with .times(n) allow repeated matching
mockPool.intercept({
path: '/api/counter',
method: 'POST',
}).reply(201, { count: 1 }).times(2);
const res2 = await request('http://example.com/api/counter', { method: 'POST' });
assert.equal(res2.statusCode, 201);
assert.deepEqual(await res2.body.json(), { count: 1 });
const res3 = await request('http://example.com/api/counter', { method: 'POST' });
assert.equal(res3.statusCode, 201);
assert.deepEqual(await res3.body.json(), { count: 1 });
await assert.rejects(
async () => request('http://example.com/api/counter', { method: 'POST' }),
(err) => err.code === 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
);
// 3. Dynamic reply callbacks receive request options
mockPool.intercept({
path: '/api/echo',
method: 'POST',
}).reply(200, (opts) => {
return {
path: opts.path,
method: opts.method,
receivedHeader: opts.headers['x-custom-header'],
receivedBody: JSON.parse(opts.body),
};
}, {
headers: { 'content-type': 'application/json' },
});
const res4 = await request('http://example.com/api/echo', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-custom-header': 'test-val-123',
},
body: JSON.stringify({ ping: 'pong' }),
});
assert.equal(res4.statusCode, 200);
const echoData = await res4.body.json();
assert.deepEqual(echoData, {
path: '/api/echo',
method: 'POST',
receivedHeader: 'test-val-123',
receivedBody: { ping: 'pong' },
});
// 4. assertNoPendingInterceptors verifies pending interceptors
mockAgent.assertNoPendingInterceptors();
// Demonstrate that unused interceptor causes assertNoPendingInterceptors to throw
const pendingPool = mockAgent.get('http://api.example.com');
pendingPool.intercept({
path: '/api/unused',
method: 'GET',
}).reply(200, 'ok');
assert.throws(
() => mockAgent.assertNoPendingInterceptors(),
(err) => {
assert.equal(err.name, 'UndiciError');
assert.equal(err.code, 'UND_ERR');
return true;
}
);
// Clean up
await mockAgent.close();
}
await main();