CodeSampleX

Пример

@sinonjs/fake-timers 10.3.0: install

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

sha256:85e22145693bae41321e75a98966e90d4b66bcf0e89e450c3873a21742427b40

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

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

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

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

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

Окружение Контракт Этапы Запуск
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-04

Кейс

HOW
Цель
verify @sinonjs/fake-timers.install in pkg:npm/%40sinonjs/fake-timers@10.3.0
Пакеты
Символы
  • @sinonjs/fake-timers.install
Окружение
node 22.23.2
Создан
2026-09-04T16:54:03Z

Контракт

  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. 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 @sinonjs/fake-timers.install in pkg:npm/%40sinonjs/fake-timers@10.3.0
Kind: HOW

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

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:1ec7a6d4a41e6e6f75d312be99942e2dd78098233fa71f498a2abcff58ce0913","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","clock.uninstall restores native global timer functions and Date"],"goal":"verify @sinonjs/fake-timers.install in pkg:npm/%40sinonjs/fake-timers@10.3.0","kind":"HOW","packages":["pkg:npm/%40sinonjs/fake-timers@10.3.0"],"schemaVersion":1,"symbols":["@sinonjs/fake-timers.install"]},"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/%40sinonjs/fake-timers@10.3.0"],"schemaVersion":1,"subject":"pkg:npm/%40sinonjs/fake-timers@10.3.0","symbols":["@sinonjs/fake-timers.install"],"verifierAdapter":"node-typescript@1"}
index.mjs
import FakeTimers from '@sinonjs/fake-timers';

export const { install } = FakeTimers;

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

export default {
  install,
  setupFakeTimers,
};
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": "10.3.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": "10.3.0",
      "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz",
      "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "@sinonjs/commons": "^3.0.0"
      }
    },
    "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": "10.3.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @sinonjs/fake-timers.install in pkg:npm/%40sinonjs/fake-timers@10.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinonjs/fake-timers@10.3.0"
  ],
  "symbols": [
    "@sinonjs/fake-timers.install"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import FakeTimers, { install, setupFakeTimers } 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: 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.');

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

аноним