CodeSampleX

Exemple

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.

Échantillon vérifié pour npm undici 8.10.0: Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net…

sha256:eabd61438b3ee2fb72c65dbb20868737ee47bc5e6f4020752114794f1179cc69

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
3
Clés de signature qui l’ont compilé
3
Environnement déclaré node linux x64 node node npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
Intercept and mock HTTP requests using MockAgent with single-use consumption, custom response callbacks, and net connect disabling in undici 8.10.0.
Paquets
Symboles
  • MockAgent
  • MockPool
  • request
  • setGlobalDispatcher
Environnement
node
Créé
2026-08-17T11:56:06Z

Contrat

  1. 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.
  2. Interceptors configured with .times(n) or .persist() allow repeated matching before being exhausted.
  3. Dynamic reply callbacks in interceptors receive the incoming request options including method, path, headers, and body.
  4. assertNoPendingInterceptors verifies that all registered interceptors were dispatched, throwing an UndiciError if any interceptor remains pending.

Fichiers

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# 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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "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"
  }
}
test/contract.mjs
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();

Seeder d'origine

csx-seed