Beispiel
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.
Verifiziertes Beispiel für npm undici 8.10.0: Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and…
sha256:eabd61438b3ee2fb72c65dbb20868737ee47bc5e6f4020752114794f1179cc69
Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen.
Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen.
MIT-0
Ausführungsbelege
Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.
- Beleggrundlage
- Signierter Vertrag bestanden
- Verifizierungsbelege
- 3
- Signaturschlüssel, die es gebaut haben
- 3
Deklarierte Umgebung
node linux x64 node node npm
Umgebungen der Verifizierungsläufe
| Umgebung | Contract | Stufen | Lauf |
|---|---|---|---|
| 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 |
Fall
HOW- Ziel
- Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net connect disabling in undici 8.10.0.
- Pakete
- Symbole
-
- MockAgent
- MockPool
- request
- setGlobalDispatcher
- Umgebung
- node
- Erstellt
- 2026-08-17T11:56:06Z
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.
Dateien
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
Quelltext
# 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();