CodeSampleX

Ejemplo

@vitest/spy 2.1.9: fn

Muestra verificada para npm @vitest/spy 2.1.9: fn. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó: fn creates mock functions that…

sha256:57a8326fe35301caf8f9c523a774a946e36091b9bf3f7f58331413755be33244

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

Caso

HOW
Objetivo
verify @vitest/spy.fn in pkg:npm/%40vitest/spy@2.1.9
Paquetes
Símbolos
  • @vitest/spy.fn
Entorno
node 22.23.2
Creado
2026-09-06T17:46:53Z

Contrato

  1. fn creates mock functions that record invocations, arguments, and return values
  2. fn defaults mock name to 'spy' in version 2.1.9 and updates it with mockName
  3. fn tracks invocation sequencing across instances in mock.invocationCallOrder
  4. fn accepts initial implementation and retrieves active handler via getMockImplementation
  5. mockImplementation overrides function behavior with custom handler
  6. mockImplementationOnce overrides behavior for a single invocation and reverts to base implementation
  7. mockReturnValue and mockReturnValueOnce configure static return values
  8. mockReturnThis configures mock function to return its calling context this
  9. mockResolvedValue and mockResolvedValueOnce configure resolved promise values
  10. mockRejectedValueOnce rejects promise with specified error
  11. withImplementation temporarily overrides mock implementation during synchronous and asynchronous execution
  12. mockClear clears recorded calls and results while preserving current implementation
  13. mockReset clears recorded history and resets implementation to return undefined
  14. mockRestore restores original function implementation provided to fn
  15. mocks registry set tracks created mock function instances
  16. isMockFunction identifies mock functions and distinguishes them from plain functions and non-callable values

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 @vitest/spy.fn in pkg:npm/%40vitest/spy@2.1.9
Kind: HOW

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

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:4a69519d067f7120f9266317f04f558e4d3dd011f6a68bbf8716179804308632","contract":["fn creates mock functions that record invocations, arguments, and return values","fn defaults mock name to 'spy' in version 2.1.9 and updates it with mockName","fn tracks invocation sequencing across instances in mock.invocationCallOrder","fn accepts initial implementation and retrieves active handler via getMockImplementation","mockImplementation overrides function behavior with custom handler","mockImplementationOnce overrides behavior for a single invocation and reverts to base implementation","mockReturnValue and mockReturnValueOnce configure static return values","mockReturnThis configures mock function to return its calling context this","mockResolvedValue and mockResolvedValueOnce configure resolved promise values","mockRejectedValueOnce rejects promise with specified error","withImplementation temporarily overrides mock implementation during synchronous and asynchronous execution","mockClear clears recorded calls and results while preserving current implementation","mockReset clears recorded history and resets implementation to return undefined","mockRestore restores original function implementation provided to fn","mocks registry set tracks created mock function instances","isMockFunction identifies mock functions and distinguishes them from plain functions and non-callable values"],"goal":"verify @vitest/spy.fn in pkg:npm/%40vitest/spy@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/spy@2.1.9"],"schemaVersion":1,"symbols":["@vitest/spy.fn"]},"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@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/spy@2.1.9","symbols":["@vitest/spy.fn"],"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 code sample for @vitest/spy@2.1.9",
  "type": "module",
  "main": "src/index.mjs",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/spy": "2.1.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/spy.fn in pkg:npm/%40vitest/spy@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/spy@2.1.9"
  ],
  "symbols": [
    "@vitest/spy.fn"
  ]
}
src/index.mjs
import { fn, isMockFunction, mocks } from '@vitest/spy';

/**
 * Creates a Vitest mock function with an optional base implementation.
 *
 * @template {(...args: any[]) => any} T
 * @param {T} [implementation] - Optional implementation for the mock function.
 * @returns {import('@vitest/spy').Mock<T>}
 */
export function createSpy(implementation) {
  return fn(implementation);
}

/**
 * Validates whether a target value is a mock function created by @vitest/spy.
 *
 * @param {unknown} value - Value to check.
 * @returns {boolean}
 */
export function checkIsMock(value) {
  return isMockFunction(value);
}

export { fn, isMockFunction, mocks };
test/contract.mjs
import assert from 'node:assert/strict';
import { fn, isMockFunction, mocks } from '@vitest/spy';
import { createSpy, checkIsMock } from '../src/index.mjs';

async function testMockCreationAndTracking() {
  const emptySpy = fn();
  assert.equal(typeof emptySpy, 'function', 'fn() must return a callable function');
  assert.equal(isMockFunction(emptySpy), true, 'isMockFunction must recognize fn() instance');
  assert.equal(checkIsMock(emptySpy), true, 'checkIsMock helper must recognize fn() instance');
  assert.equal(isMockFunction(() => {}), false, 'isMockFunction must return false for standard functions');
  assert.equal(isMockFunction(null), false, 'isMockFunction must return false for null');
  assert.equal(isMockFunction(123), false, 'isMockFunction must return false for numbers');

  assert.equal(emptySpy.getMockName(), 'spy', 'default mock name in @vitest/spy@2.1.9 must be "spy"');
  emptySpy.mockName('customAuditSpy');
  assert.equal(emptySpy.getMockName(), 'customAuditSpy', 'mockName must update assigned name');

  const defaultResult = emptySpy('param1', 100, { key: 'value' });
  assert.equal(defaultResult, undefined, 'unconfigured spy must return undefined by default');
  assert.equal(emptySpy.mock.calls.length, 1, 'mock.calls must record one call');
  assert.deepEqual(emptySpy.mock.calls[0], ['param1', 100, { key: 'value' }], 'mock.calls must record passed arguments');
  assert.equal(emptySpy.mock.results.length, 1, 'mock.results must record one result');
  assert.deepEqual(emptySpy.mock.results[0], { type: 'return', value: undefined }, 'mock.results must record return shape');

  const secondSpy = createSpy();
  secondSpy('second');
  emptySpy('first');
  assert.ok(
    secondSpy.mock.invocationCallOrder[0] < emptySpy.mock.invocationCallOrder[1],
    'invocationCallOrder must record global call sequencing'
  );
}

async function testMockImplementations() {
  const baseImplementation = (a, b) => a + b;
  const adderSpy = createSpy(baseImplementation);

  assert.equal(
    adderSpy.getMockImplementation(),
    baseImplementation,
    'getMockImplementation should return initial implementation'
  );
  assert.equal(adderSpy(10, 25), 35, 'initial implementation should be executed');
  assert.deepEqual(adderSpy.mock.calls[0], [10, 25]);
  assert.deepEqual(adderSpy.mock.results[0], { type: 'return', value: 35 });

  const customMultiplier = (a, b) => a * b;
  adderSpy.mockImplementation(customMultiplier);
  assert.equal(
    adderSpy.getMockImplementation(),
    customMultiplier,
    'getMockImplementation should return updated implementation'
  );
  assert.equal(adderSpy(4, 6), 24, 'mockImplementation should override function behavior');

  adderSpy.mockImplementationOnce((a, b) => a - b);
  assert.equal(adderSpy(20, 5), 15, 'mockImplementationOnce should be used on next invocation');
  assert.equal(adderSpy(4, 6), 24, 'subsequent invocation should fall back to base implementation');
}

async function testReturnValueHelpers() {
  const returnSpy = fn();
  returnSpy.mockReturnValue('static-default');
  returnSpy.mockReturnValueOnce('one-time-first');
  returnSpy.mockReturnValueOnce('one-time-second');

  assert.equal(returnSpy(), 'one-time-first', 'mockReturnValueOnce should provide first return value');
  assert.equal(returnSpy(), 'one-time-second', 'mockReturnValueOnce should provide second return value');
  assert.equal(returnSpy(), 'static-default', 'mockReturnValue should provide default on subsequent calls');
  assert.equal(returnSpy(), 'static-default', 'mockReturnValue should persist');

  const contextHost = {
    chainable: fn().mockReturnThis()
  };
  assert.equal(contextHost.chainable(), contextHost, 'mockReturnThis should return this context');
}

async function testAsyncPromiseHelpers() {
  const asyncSpy = fn();
  asyncSpy.mockResolvedValue('resolved-default');
  asyncSpy.mockResolvedValueOnce('resolved-once');

  assert.equal(await asyncSpy(), 'resolved-once', 'mockResolvedValueOnce should resolve first promise');
  assert.equal(await asyncSpy(), 'resolved-default', 'mockResolvedValue should resolve subsequent promises');

  const failureSpy = fn();
  failureSpy.mockRejectedValueOnce(new Error('simulated async rejection'));
  await assert.rejects(
    async () => { await failureSpy(); },
    { name: 'Error', message: 'simulated async rejection' },
    'mockRejectedValueOnce should reject promise with given error'
  );
}

async function testTemporaryImplementation() {
  const tempSpy = fn(() => 'default-val');

  const returnedSpy = tempSpy.withImplementation(() => 'temp-sync-val', () => {
    assert.equal(tempSpy(), 'temp-sync-val', 'temporary implementation should run inside callback');
  });
  assert.equal(returnedSpy, tempSpy, 'withImplementation should return the spy instance');
  assert.equal(tempSpy(), 'default-val', 'original implementation must be restored after sync callback');

  await tempSpy.withImplementation(() => 'temp-async-val', async () => {
    assert.equal(tempSpy(), 'temp-async-val', 'temporary implementation should run inside async callback');
  });
  assert.equal(tempSpy(), 'default-val', 'original implementation must be restored after async callback');
}

async function testLifecycleAndRegistry() {
  const lifecycleSpy = fn((n) => n * 3);
  lifecycleSpy(2);
  lifecycleSpy(4);
  assert.equal(lifecycleSpy.mock.calls.length, 2, 'recorded 2 calls');

  lifecycleSpy.mockClear();
  assert.equal(lifecycleSpy.mock.calls.length, 0, 'mockClear should empty call history');
  assert.equal(lifecycleSpy.mock.results.length, 0, 'mockClear should empty results history');
  assert.equal(lifecycleSpy(5), 15, 'mockClear should keep function implementation intact');

  lifecycleSpy.mockReset();
  assert.equal(lifecycleSpy.mock.calls.length, 0, 'mockReset should clear call history');
  assert.equal(lifecycleSpy(5), undefined, 'mockReset should reset implementation to return undefined');

  const originalHandler = (x) => x + 50;
  const restoreSpy = fn(originalHandler);
  restoreSpy.mockImplementation((x) => x + 9999);
  assert.equal(restoreSpy(1), 10000, 'mockImplementation active');
  restoreSpy.mockRestore();
  assert.equal(restoreSpy(1), 51, 'mockRestore should restore initial function passed to fn');

  assert.ok(mocks.has(restoreSpy), 'mocks Set registry must include created spy instance');
}

async function runAllContracts() {
  await testMockCreationAndTracking();
  await testMockImplementations();
  await testReturnValueHelpers();
  await testAsyncPromiseHelpers();
  await testTemporaryImplementation();
  await testLifecycleAndRegistry();
  console.log('All @vitest/spy@2.1.9 contract assertions passed successfully.');
}

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

Seeder de origen

anónimo