CodeSampleX

示例

@vitest/spy 2.1.9: spy function and method interception with spyOn

已验证示例 — npm @vitest/spy 2.1.9: spy function and method interception with spyOn. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:e35514e4e82d76baee2505566f1d4da95f8ac6a74e87ab59f364cf9f9fbbc7ae

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
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-08-26

案例

HOW
目标
spy function and method interception with spyOn
包
符号
  • fn
  • spyOn
环境
node 22.23.2
创建时间
2026-08-26T14:49:08Z

契约

  1. fn creates mock functions that record invocations, arguments, and return values
  2. fn supports mockImplementationOnce for one-time overrides and falls back to base implementation
  3. fn supports mockClear to reset call history without clearing implementation
  4. fn supports mockReturnValue, mockReturnValueOnce, mockResolvedValueOnce, and mockRejectedValueOnce
  5. spyOn wraps existing object methods and tracks invocations while delegating to original implementation
  6. spyOn mockImplementation overrides method behavior with custom handler
  7. spyOn mockRestore restores original method implementation and resets recorded calls
  8. spyOn intercepts getter and setter property accessors with restore support
  9. isMockFunction identifies mock functions and spy wrappers

文件

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

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: spy function and method interception with spyOn
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/spy@2.1.9
Demonstrate these symbols/APIs:
  - fn
  - spyOn

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:5fb474adaf11595af0b894a566476918ca968f43b627caf5250291342fb2ebe1","contract":["fn creates mock functions that record invocations, arguments, and return values","fn supports mockImplementationOnce for one-time overrides and falls back to base implementation","fn supports mockClear to reset call history without clearing implementation","fn supports mockReturnValue, mockReturnValueOnce, mockResolvedValueOnce, and mockRejectedValueOnce","spyOn wraps existing object methods and tracks invocations while delegating to original implementation","spyOn mockImplementation overrides method behavior with custom handler","spyOn mockRestore restores original method implementation and resets recorded calls","spyOn intercepts getter and setter property accessors with restore support","isMockFunction identifies mock functions and spy wrappers"],"goal":"spy function and method interception with spyOn","kind":"HOW","packages":["pkg:npm/%40vitest/spy@2.1.9"],"schemaVersion":1,"symbols":["fn","spyOn"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/spy@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/spy@2.1.9","symbols":["fn","spyOn"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-vitest-spy",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-spy",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/spy": "2.1.9"
      }
    },
    "node_modules/@vitest/spy": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
      "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
      "license": "MIT",
      "dependencies": {
        "tinyspy": "^3.0.2"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/tinyspy": {
      "version": "3.0.2",
      "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
      "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-spy",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for fn and spyOn in @vitest/spy@2.1.9",
  "main": "test/contract.mjs",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/spy": "2.1.9"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "spy function and method interception with spyOn",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/spy@2.1.9"
  ],
  "symbols": [
    "fn",
    "spyOn"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import { fn, spyOn, isMockFunction, mocks } from '@vitest/spy';

async function testFnCreationAndCallTracking() {
  const mockAdder = fn((a, b) => a + b);
  assert.strictEqual(isMockFunction(mockAdder), true, 'fn instance should be recognized as mock function');
  assert.strictEqual(mockAdder.getMockName(), 'spy', 'default mock name should be spy');

  const result1 = mockAdder(10, 20);
  assert.strictEqual(result1, 30, 'mock implementation should return sum');
  assert.strictEqual(mockAdder.mock.calls.length, 1, 'mock should record 1 call');
  assert.deepStrictEqual(mockAdder.mock.calls[0], [10, 20], 'call arguments should match');
  assert.deepStrictEqual(mockAdder.mock.results[0], { type: 'return', value: 30 }, 'mock result should record return');

  mockAdder.mockImplementationOnce((a, b) => a * b);
  const result2 = mockAdder(5, 6);
  assert.strictEqual(result2, 30, 'mockImplementationOnce should override implementation for one call');

  const result3 = mockAdder(2, 3);
  assert.strictEqual(result3, 5, 'mock should fallback to original implementation after one-time override');
  assert.strictEqual(mockAdder.mock.calls.length, 3, 'mock should have recorded 3 calls');

  mockAdder.mockClear();
  assert.strictEqual(mockAdder.mock.calls.length, 0, 'mockClear should clear call history');
  assert.strictEqual(mockAdder(1, 1), 2, 'implementation should remain intact after clear');
}

async function testFnReturnAndResolutionOverrides() {
  const valueMock = fn();

  valueMock.mockReturnValue('default-val');
  valueMock.mockReturnValueOnce('first-val');
  valueMock.mockReturnValueOnce('second-val');

  assert.strictEqual(valueMock(), 'first-val', 'first call should return first-val');
  assert.strictEqual(valueMock(), 'second-val', 'second call should return second-val');
  assert.strictEqual(valueMock(), 'default-val', 'subsequent calls should return default-val');

  const asyncMock = fn();
  asyncMock.mockResolvedValueOnce('async-ok');
  asyncMock.mockRejectedValueOnce(new Error('async-fail'));

  const resolved = await asyncMock();
  assert.strictEqual(resolved, 'async-ok', 'mockResolvedValueOnce should resolve with value');

  await assert.rejects(
    async () => { await asyncMock(); },
    { message: 'async-fail' },
    'mockRejectedValueOnce should reject with error'
  );
}

async function testSpyOnMethodInterceptionAndRestore() {
  const service = {
    multiplier: 2,
    process(n) {
      return n * this.multiplier;
    }
  };

  const spy = spyOn(service, 'process');
  assert.strictEqual(isMockFunction(spy), true, 'spyOn returns a mock function');
  assert.ok(mocks.has(spy), 'spy should be registered in mocks set');

  const output1 = service.process(7);
  assert.strictEqual(output1, 14, 'original method should execute by default');
  assert.strictEqual(spy.mock.calls.length, 1, 'spy should record invocation');
  assert.deepStrictEqual(spy.mock.calls[0], [7], 'spy should record argument 7');

  spy.mockImplementation((n) => n + 100);
  const output2 = service.process(7);
  assert.strictEqual(output2, 107, 'spy should override implementation');

  spy.mockRestore();
  const output3 = service.process(7);
  assert.strictEqual(output3, 14, 'mockRestore should restore original method');
  assert.strictEqual(spy.mock.calls.length, 0, 'mockRestore resets mock calls and stops interception');
}

async function testSpyOnGettersAndSetters() {
  const store = {
    _token: 'alpha',
    get token() {
      return this._token;
    },
    set token(val) {
      this._token = val;
    }
  };

  const getSpy = spyOn(store, 'token', 'get').mockReturnValue('intercepted-token');
  assert.strictEqual(store.token, 'intercepted-token', 'getter spy should intercept property read');
  assert.strictEqual(getSpy.mock.calls.length, 1, 'getter spy should record access');

  getSpy.mockRestore();
  assert.strictEqual(store.token, 'alpha', 'restored getter should return underlying value');

  let setterCalls = 0;
  const setSpy = spyOn(store, 'token', 'set').mockImplementation((val) => {
    setterCalls += 1;
    store._token = val.toUpperCase();
  });

  store.token = 'beta';
  assert.strictEqual(setterCalls, 1, 'setter spy should intercept property assignment');
  assert.strictEqual(store._token, 'BETA', 'custom setter implementation should execute');

  setSpy.mockRestore();
  store.token = 'gamma';
  assert.strictEqual(store._token, 'gamma', 'restored setter should use original accessor');
}

async function main() {
  await testFnCreationAndCallTracking();
  await testFnReturnAndResolutionOverrides();
  await testSpyOnMethodInterceptionAndRestore();
  await testSpyOnGettersAndSetters();
  console.log('Contract tests passed successfully.');
}

main().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名