CodeSampleX

샘플

@vitest/spy 4.1.11: fn, isMockFunction, spyOn

검증된 샘플 — npm @vitest/spy 4.1.11: fn, isMockFunction, spyOn. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: fn creates mock functions that record…

sha256:a6c554933ccfe3921c9827e9ecd442480567abe285aea98c9493eca5ac3c23f0

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

케이스

HOW
목표
verify pkg:npm/%40vitest/spy@4.1.11
패키지
심벌
  • fn
  • isMockFunction
  • spyOn
환경
node 22.23.2
생성일
2026-08-28T06:22:46Z

컨트랙트

  1. fn creates mock functions that record invocations, arguments, and return values
  2. fn defaults mock name to 'vi.fn()' and updates it with mockName
  3. fn supports mockImplementationOnce for one-time overrides and falls back to base implementation
  4. fn supports mockClear to reset call history without clearing implementation
  5. fn supports mockReturnValue, mockReturnValueOnce, mockResolvedValueOnce, and mockRejectedValueOnce
  6. spyOn wraps existing object methods and tracks invocations while delegating to original implementation
  7. spyOn mockImplementation overrides method behavior with custom handler
  8. spyOn mockRestore restores original method implementation and resets recorded calls
  9. spyOn intercepts getter and setter property accessors with restore support
  10. 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: verify pkg:npm/%40vitest/spy@4.1.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/spy@4.1.11
Demonstrate these symbols/APIs:
  - fn
  - isMockFunction
  - 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:a87ba25799bb1ccd2413e46fc52d1b826d378596f1adaf521a48d209d59627ce","contract":["fn creates mock functions that record invocations, arguments, and return values","fn defaults mock name to 'vi.fn()' and updates it with mockName","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":"verify pkg:npm/%40vitest/spy@4.1.11","kind":"HOW","packages":["pkg:npm/%40vitest/spy@4.1.11"],"schemaVersion":1,"symbols":["fn","isMockFunction","spyOn"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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@4.1.11"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/spy@4.1.11","symbols":["fn","isMockFunction","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": "4.1.11"
      }
    },
    "node_modules/@vitest/spy": {
      "version": "4.1.11",
      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
      "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
      "license": "MIT",
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-spy",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification for fn, isMockFunction, and spyOn in @vitest/spy@4.1.11",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/spy": "4.1.11"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40vitest/spy@4.1.11",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/spy@4.1.11"
  ],
  "symbols": [
    "fn",
    "isMockFunction",
    "spyOn"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import { fn, spyOn, isMockFunction, clearAllMocks, resetAllMocks, restoreAllMocks } 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(isMockFunction(() => {}), false, 'plain function should not be recognized as mock function');
  assert.strictEqual(isMockFunction(null), false, 'null should not be recognized as mock function');
  assert.strictEqual(mockAdder.getMockName(), 'vi.fn()', 'default mock name in v4 should be vi.fn()');

  mockAdder.mockName('adderMock');
  assert.strictEqual(mockAdder.getMockName(), 'adderMock', 'mockName should update mock name');

  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 mockClear');
}

async function testFnReturnAndResolutionOverrides() {
  const valueMock = fn();
  assert.strictEqual(isMockFunction(valueMock), true, 'empty fn instance should be recognized as mock function');

  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.strictEqual(spy.getMockName(), 'process', 'spyOn mock name should match method name');

  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);
});

오리진 시더

익명