CodeSampleX

Пример

@sinonjs/fake-timers 15.4.0: install, withGlobal

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

sha256:96447dcd5d5b19e99cb5ab2aeb60c9b28d54a22b7c47d623ac6a563b9abab4dd

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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
Цель
verify pkg:npm/%40sinonjs/fake-timers@15.4.0
Пакеты
Символы
  • @sinonjs/fake-timers.install
  • @sinonjs/fake-timers.withGlobal
Окружение
node 22.23.2
Создан
2026-08-26T07:44:57Z

Контракт

  1. install replaces global timer functions and initializes now to configured timestamp
  2. global setTimeout and clearTimeout are controlled by fake clock tick
  3. global setInterval and clearInterval repeat and stop as time advances
  4. clock.tickAsync advances time and awaits asynchronous timer callbacks
  5. clock.setSystemTime updates Date.now without triggering scheduled timer callbacks
  6. clock.runAll executes all scheduled timers across global queue
  7. clock.next advances time to the timestamp of the next scheduled timer and executes it
  8. clock.countTimers reports the current count of pending scheduled timers
  9. clock.jump advances time by specified milliseconds and fires scheduled callbacks
  10. withGlobal provides fake timer functions bound to a custom context object
  11. clock.uninstall restores native global timer functions and Date

Файлы

  • 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 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
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:9b0e6dd223b0d60646a5a738dcc7430dbbeb72328e624c7235ad624d9a7eaee8","constraints":{"executionContext":"node"},"contract":["install replaces global timer functions and initializes now to configured timestamp","global setTimeout and clearTimeout are controlled by fake clock tick","global setInterval and clearInterval repeat and stop as time advances","clock.tickAsync advances time and awaits asynchronous timer callbacks","clock.setSystemTime updates Date.now without triggering scheduled timer callbacks","clock.runAll executes all scheduled timers across global queue","clock.next advances time to the timestamp of the next scheduled timer and executes it","clock.countTimers reports the current count of pending scheduled timers","clock.jump advances time by specified milliseconds and fires scheduled callbacks","withGlobal provides fake timer functions bound to a custom context object","clock.uninstall restores native global timer functions and Date"],"goal":"verify 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.install","@sinonjs/fake-timers.withGlobal"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","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.install","@sinonjs/fake-timers.withGlobal"],"verifierAdapter":"node-typescript@1"}
index.mjs
import FakeTimers from '@sinonjs/fake-timers';

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

/**
 * Installs fake timers globally with the given configuration options.
 *
 * @param {import('@sinonjs/fake-timers').FakeTimerInstallOpts} [config={}] - Installation options
 * @returns {import('@sinonjs/fake-timers').InstalledClock} Clock instance controlling global timers
 */
export function setupFakeTimers(config = {}) {
  return install(config);
}

/**
 * Creates fake timer methods bound to a specific global context object.
 *
 * @param {object} globalObject - The global context object to bind
 * @returns {typeof FakeTimers} FakeTimers module bound to the context
 */
export function createWithGlobal(globalObject) {
  return withGlobal(globalObject);
}

export default {
  install,
  withGlobal,
  createClock,
  setupFakeTimers,
  createWithGlobal,
};
package-lock.json
{
  "name": "sample-fake-timers-install",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-fake-timers-install",
      "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-install",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@sinonjs/fake-timers": "15.4.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40sinonjs/fake-timers@15.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinonjs/fake-timers@15.4.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import FakeTimers, { install, setupFakeTimers, withGlobal, createWithGlobal } from '../index.mjs';

// Contract 1: install replaces global timer functions and initializes now to configured timestamp
{
  const initialTimestamp = 1700000000000;
  const originalSetTimeout = globalThis.setTimeout;
  const originalDateNow = Date.now;

  const clock = setupFakeTimers({ now: initialTimestamp });
  try {
    assert.strictEqual(typeof install, 'function');
    assert.strictEqual(typeof clock.tick, 'function');
    assert.strictEqual(typeof clock.tickAsync, 'function');
    assert.strictEqual(typeof clock.uninstall, 'function');
    assert.strictEqual(typeof clock.runAll, 'function');
    assert.strictEqual(typeof clock.setSystemTime, 'function');
    assert.strictEqual(typeof clock.countTimers, 'function');
    assert.strictEqual(typeof clock.next, 'function');
    assert.strictEqual(typeof clock.jump, 'function');
    assert.strictEqual(clock.now, initialTimestamp);
    assert.strictEqual(Date.now(), initialTimestamp);
    assert.notStrictEqual(globalThis.setTimeout, originalSetTimeout);
  } finally {
    clock.uninstall();
    assert.strictEqual(globalThis.setTimeout, originalSetTimeout);
    assert.strictEqual(Date.now, originalDateNow);
  }
}

// Contract 2: global setTimeout and clearTimeout are controlled by fake clock tick
{
  const clock = install({ now: 1000 });
  try {
    let executed = false;
    let receivedArg = null;
    const timerId = setTimeout((val) => {
      executed = true;
      receivedArg = val;
    }, 200, 'payload');

    assert.strictEqual(executed, false);
    clock.tick(199);
    assert.strictEqual(executed, false);
    assert.strictEqual(clock.now, 1199);

    clock.tick(1);
    assert.strictEqual(executed, true);
    assert.strictEqual(receivedArg, 'payload');
    assert.strictEqual(clock.now, 1200);

    let cancelledExecuted = false;
    const cancelId = setTimeout(() => {
      cancelledExecuted = true;
    }, 100);
    clearTimeout(cancelId);
    clock.tick(200);
    assert.strictEqual(cancelledExecuted, false);
  } finally {
    clock.uninstall();
  }
}

// Contract 3: global setInterval and clearInterval repeat and stop as time advances
{
  const clock = install({ now: 0 });
  try {
    let runs = 0;
    const intervalId = setInterval(() => {
      runs++;
    }, 50);

    clock.tick(125);
    assert.strictEqual(runs, 2);

    clock.tick(50);
    assert.strictEqual(runs, 3);

    clearInterval(intervalId);
    clock.tick(100);
    assert.strictEqual(runs, 3);
  } finally {
    clock.uninstall();
  }
}

// Contract 4: clock.tickAsync advances time and awaits asynchronous timer callbacks
{
  const clock = install({ now: 0 });
  try {
    let asyncCompleted = false;
    setTimeout(async () => {
      await Promise.resolve();
      asyncCompleted = true;
    }, 100);

    assert.strictEqual(asyncCompleted, false);
    await clock.tickAsync(100);
    assert.strictEqual(asyncCompleted, true);
  } finally {
    clock.uninstall();
  }
}

// Contract 5: clock.setSystemTime updates Date.now without triggering scheduled timer callbacks
{
  const clock = install({ now: 1000 });
  try {
    let fired = false;
    setTimeout(() => {
      fired = true;
    }, 500);

    clock.setSystemTime(5000);
    assert.strictEqual(clock.now, 5000);
    assert.strictEqual(Date.now(), 5000);
    assert.strictEqual(fired, false);
    assert.strictEqual(clock.countTimers(), 1);
  } finally {
    clock.uninstall();
  }
}

// Contract 6: clock.runAll executes all scheduled timers across global queue
{
  const clock = install({ now: 0 });
  try {
    const executed = [];
    setTimeout(() => executed.push('first'), 50);
    setTimeout(() => executed.push('third'), 150);
    setTimeout(() => executed.push('second'), 100);

    assert.strictEqual(clock.countTimers(), 3);
    clock.runAll();
    assert.deepEqual(executed, ['first', 'second', 'third']);
    assert.strictEqual(clock.countTimers(), 0);
    assert.strictEqual(clock.now, 150);
  } finally {
    clock.uninstall();
  }
}

// Contract 7: clock.next advances time to the timestamp of the next scheduled timer and executes it
{
  const clock = install({ now: 0 });
  try {
    const log = [];
    setTimeout(() => log.push('a'), 100);
    setTimeout(() => log.push('b'), 250);

    clock.next();
    assert.deepEqual(log, ['a']);
    assert.strictEqual(clock.now, 100);
    assert.strictEqual(clock.countTimers(), 1);

    clock.next();
    assert.deepEqual(log, ['a', 'b']);
    assert.strictEqual(clock.now, 250);
    assert.strictEqual(clock.countTimers(), 0);
  } finally {
    clock.uninstall();
  }
}

// Contract 8: clock.countTimers reports the current count of pending scheduled timers
{
  const clock = install({ now: 0 });
  try {
    assert.strictEqual(clock.countTimers(), 0);
    const t1 = setTimeout(() => {}, 100);
    const t2 = setTimeout(() => {}, 200);
    const t3 = setInterval(() => {}, 50);
    assert.strictEqual(clock.countTimers(), 3);

    clearTimeout(t1);
    assert.strictEqual(clock.countTimers(), 2);

    clearInterval(t3);
    assert.strictEqual(clock.countTimers(), 1);

    clearTimeout(t2);
    assert.strictEqual(clock.countTimers(), 0);
  } finally {
    clock.uninstall();
  }
}

// Contract 9: clock.jump advances time by specified milliseconds and fires scheduled callbacks
{
  const clock = install({ now: 0 });
  try {
    let called = false;
    setTimeout(() => {
      called = true;
    }, 500);

    clock.jump(600);
    assert.strictEqual(called, true);
    assert.strictEqual(clock.now, 600);
  } finally {
    clock.uninstall();
  }
}

// Contract 10: withGlobal provides fake timer functions bound to a custom context object
{
  const customContext = {
    Date: Date,
    setTimeout: globalThis.setTimeout,
    clearTimeout: globalThis.clearTimeout,
  };
  const scopedFakeTimers = createWithGlobal(customContext);
  assert.strictEqual(typeof scopedFakeTimers.createClock, 'function');
  assert.strictEqual(typeof scopedFakeTimers.install, 'function');

  const scopedClock = scopedFakeTimers.createClock(500);
  assert.strictEqual(scopedClock.now, 500);
}

// Contract 11: clock.uninstall restores native global timer functions and Date
{
  const nativeSetTimeout = globalThis.setTimeout;
  const nativeDate = globalThis.Date;

  const clock = install({ now: 12345 });
  assert.notStrictEqual(globalThis.setTimeout, nativeSetTimeout);

  clock.uninstall();
  assert.strictEqual(globalThis.setTimeout, nativeSetTimeout);
  assert.strictEqual(globalThis.Date, nativeDate);
}

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

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

аноним