CodeSampleX

Пример

@sinonjs/fake-timers 15.4.0: timers

Проверенный пример — npm @sinonjs/fake-timers 15.4.0: timers. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:f7be567d5e9ba5601c8ed4888f746fa743bfb72ccb43d04e96d988b9cb3a8ec2

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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
Цель
verify @sinonjs/fake-timers.timers in pkg:npm/%40sinonjs/fake-timers@15.4.0
Пакеты
Символы
  • @sinonjs/fake-timers.timers
Создан
2026-08-26T07:48:36Z

Контракт

  1. timers contains original timer methods and constructors
  2. timers.setTimeout and clearTimeout remain native while global timers are mocked
  3. timers.setInterval and clearInterval remain native during clock installation
  4. timers.Date preserves native Date constructor when global Date is mocked
  5. timers.nextTick and timers.hrtime map to process timing functions in node
  6. withGlobal creates scoped timers object reflecting the custom global context
  7. runWithNativeTimeout executes using native timer even when fake timers are active

Файлы

  • PROMPT.md
  • csx.json
  • index.mjs
  • 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 @sinonjs/fake-timers.timers in pkg:npm/%40sinonjs/fake-timers@15.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40sinonjs/fake-timers@15.4.0
Demonstrate these symbols/APIs:
  - @sinonjs/fake-timers.timers

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:2621f53ea9cf35472f63714d9eb8fcd71deff9b843036f6eee2a85300896aebd","contract":["timers contains original timer methods and constructors","timers.setTimeout and clearTimeout remain native while global timers are mocked","timers.setInterval and clearInterval remain native during clock installation","timers.Date preserves native Date constructor when global Date is mocked","timers.nextTick and timers.hrtime map to process timing functions in node","withGlobal creates scoped timers object reflecting the custom global context","runWithNativeTimeout executes using native timer even when fake timers are active"],"goal":"verify @sinonjs/fake-timers.timers in pkg:npm/%40sinonjs/fake-timers@15.4.0","kind":"HOW","packages":["pkg:npm/%40sinonjs/fake-timers@15.4.0"],"schemaVersion":1,"symbols":["@sinonjs/fake-timers.timers"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40sinonjs/fake-timers@15.4.0"],"schemaVersion":1,"subject":"pkg:npm/%40sinonjs/fake-timers@15.4.0","symbols":["@sinonjs/fake-timers.timers"],"verifierAdapter":"node-typescript@1"}
index.mjs
import FakeTimers from '@sinonjs/fake-timers';

export const { timers, install, withGlobal, createClock } = FakeTimers;

/**
 * Returns the object containing references to the original, un-mocked timer functions.
 *
 * @returns {typeof FakeTimers.timers} The un-mocked timer functions
 */
export function getOriginalTimers() {
  return FakeTimers.timers;
}

/**
 * Returns the timer functions captured from a custom global context.
 *
 * @param {object} customGlobal - Global context object
 * @returns {object} Timer functions captured from the context
 */
export function getCustomTimers(customGlobal) {
  const scoped = withGlobal(customGlobal);
  return scoped.timers;
}

/**
 * Executes a callback after delay ms using the native, un-mocked setTimeout.
 *
 * @param {Function} callback - Callback to execute
 * @param {number} delayMs - Delay in milliseconds
 * @returns {any} Native timer identifier
 */
export function runWithNativeTimeout(callback, delayMs) {
  return FakeTimers.timers.setTimeout(callback, delayMs);
}

export default {
  timers,
  install,
  withGlobal,
  createClock,
  getOriginalTimers,
  getCustomTimers,
  runWithNativeTimeout,
};
package-lock.json
{
  "name": "sample-fake-timers-timers",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-fake-timers-timers",
      "version": "1.0.0",
      "dependencies": {
        "@sinonjs/fake-timers": "15.4.0"
      }
    },
    "node_modules/@sinonjs/commons": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz",
      "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "type-detect": "4.0.8"
      }
    },
    "node_modules/@sinonjs/fake-timers": {
      "version": "15.4.0",
      "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-15.4.0.tgz",
      "integrity": "sha512-DsG+8/LscQIQg68J6Ef3dv10u6nVyetYn923s3/sus5eaGfTo1of5WMZSLf0UJc9KDuKPilPH0UDJCjvNbDNCA==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "@sinonjs/commons": "^3.0.1"
      }
    },
    "node_modules/type-detect": {
      "version": "4.0.8",
      "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
      "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
      "license": "MIT",
      "engines": {
        "node": ">=4"
      }
    }
  }
}
package.json
{
  "name": "sample-fake-timers-timers",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@sinonjs/fake-timers": "15.4.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @sinonjs/fake-timers.timers in pkg:npm/%40sinonjs/fake-timers@15.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinonjs/fake-timers@15.4.0"
  ],
  "symbols": [
    "@sinonjs/fake-timers.timers"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import FakeTimers, {
  timers,
  install,
  getOriginalTimers,
  getCustomTimers,
  runWithNativeTimeout,
} from '../index.mjs';

// Contract 1: timers contains original timer methods and constructors
{
  const originalTimers = getOriginalTimers();
  assert.strictEqual(typeof originalTimers, 'object');
  assert.strictEqual(typeof originalTimers.setTimeout, 'function');
  assert.strictEqual(typeof originalTimers.clearTimeout, 'function');
  assert.strictEqual(typeof originalTimers.setInterval, 'function');
  assert.strictEqual(typeof originalTimers.clearInterval, 'function');
  assert.strictEqual(typeof originalTimers.Date, 'function');
  assert.strictEqual(typeof originalTimers.setImmediate, 'function');
  assert.strictEqual(typeof originalTimers.clearImmediate, 'function');
  assert.strictEqual(typeof originalTimers.hrtime, 'function');
  assert.strictEqual(typeof originalTimers.nextTick, 'function');
  assert.strictEqual(typeof originalTimers.queueMicrotask, 'function');
}

// Contract 2: timers.setTimeout and clearTimeout remain native while global timers are mocked
{
  const nativeSetTimeout = globalThis.setTimeout;
  const nativeClearTimeout = globalThis.clearTimeout;

  assert.strictEqual(timers.setTimeout, nativeSetTimeout);
  assert.strictEqual(timers.clearTimeout, nativeClearTimeout);

  const clock = install({ now: 1000 });
  try {
    assert.notStrictEqual(globalThis.setTimeout, nativeSetTimeout);
    assert.notStrictEqual(globalThis.clearTimeout, nativeClearTimeout);
    assert.strictEqual(timers.setTimeout, nativeSetTimeout);
    assert.strictEqual(timers.clearTimeout, nativeClearTimeout);
  } finally {
    clock.uninstall();
    assert.strictEqual(globalThis.setTimeout, nativeSetTimeout);
    assert.strictEqual(globalThis.clearTimeout, nativeClearTimeout);
  }
}

// Contract 3: timers.setInterval and clearInterval remain native during clock installation
{
  const nativeSetInterval = globalThis.setInterval;
  const nativeClearInterval = globalThis.clearInterval;

  assert.strictEqual(timers.setInterval, nativeSetInterval);
  assert.strictEqual(timers.clearInterval, nativeClearInterval);

  const clock = install({ now: 0 });
  try {
    assert.notStrictEqual(globalThis.setInterval, nativeSetInterval);
    assert.notStrictEqual(globalThis.clearInterval, nativeClearInterval);
    assert.strictEqual(timers.setInterval, nativeSetInterval);
    assert.strictEqual(timers.clearInterval, nativeClearInterval);
  } finally {
    clock.uninstall();
  }
}

// Contract 4: timers.Date preserves native Date constructor when global Date is mocked
{
  const nativeDate = globalThis.Date;
  assert.strictEqual(timers.Date, nativeDate);

  const clock = install({ now: 5000 });
  try {
    assert.notStrictEqual(globalThis.Date, nativeDate);
    assert.strictEqual(timers.Date, nativeDate);
    assert.strictEqual(new timers.Date().getTime() !== 5000 || Date.now() === 5000, true);
  } finally {
    clock.uninstall();
    assert.strictEqual(globalThis.Date, nativeDate);
  }
}

// Contract 5: timers.nextTick and timers.hrtime map to process timing functions in node
{
  assert.strictEqual(timers.nextTick, process.nextTick);
  assert.strictEqual(timers.hrtime, process.hrtime);
}

// Contract 6: withGlobal creates scoped timers object reflecting the custom global context
{
  const customSetTimeout = () => 'custom-timer';
  const customContext = {
    setTimeout: customSetTimeout,
    clearTimeout: () => {},
    setInterval: () => {},
    clearInterval: () => {},
    Date: class CustomDate {},
  };

  const scopedTimers = getCustomTimers(customContext);
  assert.strictEqual(scopedTimers.setTimeout, customSetTimeout);
  assert.strictEqual(scopedTimers.Date, customContext.Date);
  assert.strictEqual(scopedTimers.setImmediate, undefined);
}

// Contract 7: runWithNativeTimeout executes using native timer even when fake timers are active
{
  const clock = install({ now: 0 });
  try {
    let nativeRan = false;
    await new Promise((resolve) => {
      const timerId = runWithNativeTimeout(() => {
        nativeRan = true;
        resolve();
      }, 10);
      assert.ok(timerId);
    });
    assert.strictEqual(nativeRan, true);
    assert.strictEqual(clock.now, 0);
  } finally {
    clock.uninstall();
  }
}

console.log('All contracts passed.');

Исходный сидер

аноним