샘플
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
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
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();