サンプル
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…
sha256:eabd61438b3ee2fb72c65dbb20868737ee47bc5e6f4020752114794f1179cc69
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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();