Пример
jest-mock 29.7.0: spyOn
Проверенный пример — npm jest-mock 29.7.0: spyOn. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: spyOn wraps an object method…
sha256:5ba4289702e318094ccbda4ec02b72501afc0cbb1770f12d5e4c8f4cb6a5a56f
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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-06 |
Кейс
HOW- Цель
- verify jest-mock.spyOn in pkg:npm/jest-mock@29.7.0
- Пакеты
- Символы
-
- jest-mock.spyOn
- Окружение
- node 22.23.2
- Создан
- 2026-09-06T09:26:29Z
Контракт
- spyOn wraps an object method, intercepts invocations, and delegates to the original implementation while recording calls and results
- spyOn mockImplementation replaces method execution logic dynamically while continuing call tracking
- spyOn mockReturnValue and mockReturnValueOnce provide default and one-time return values
- spyOn mockResolvedValue and mockResolvedValueOnce handle asynchronous method resolutions
- spyOn supports getter and setter property accessors with 'get' and 'set' accessType
- spyOn mockRestore restores original method and resets spy call state
- spyOn mockClear and mockReset manage recorded invocations and mock implementation state
Файлы
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Исходный код
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 jest-mock.spyOn in pkg:npm/jest-mock@29.7.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jest-mock@29.7.0
Demonstrate these symbols/APIs:
- jest-mock.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.
{"case":{"caseId":"case:sha256:adbc37da870658756992abff1f2c2f0bf928d060784960d7fd2cce3f74554950","contract":["spyOn wraps an object method, intercepts invocations, and delegates to the original implementation while recording calls and results","spyOn mockImplementation replaces method execution logic dynamically while continuing call tracking","spyOn mockReturnValue and mockReturnValueOnce provide default and one-time return values","spyOn mockResolvedValue and mockResolvedValueOnce handle asynchronous method resolutions","spyOn supports getter and setter property accessors with 'get' and 'set' accessType","spyOn mockRestore restores original method and resets spy call state","spyOn mockClear and mockReset manage recorded invocations and mock implementation state"],"goal":"verify jest-mock.spyOn in pkg:npm/jest-mock@29.7.0","kind":"HOW","packages":["pkg:npm/jest-mock@29.7.0"],"schemaVersion":1,"symbols":["jest-mock.spyOn"]},"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/jest-mock@29.7.0"],"schemaVersion":1,"subject":"pkg:npm/jest-mock@29.7.0","symbols":["jest-mock.spyOn"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-jest-mock-spy-on",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-jest-mock-spy-on",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"jest-mock": "29.7.0"
}
},
"node_modules/@jest/schemas": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
"integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
"license": "MIT",
"dependencies": {
"@sinclair/typebox": "^0.27.8"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/@jest/types": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz",
"integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==",
"license": "MIT",
"dependencies": {
"@jest/schemas": "^29.6.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
"@types/yargs": "^17.0.8",
"chalk": "^4.0.0"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/@sinclair/typebox": {
"version": "0.27.12",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
"integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==",
"license": "MIT"
},
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
"integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
"license": "MIT"
},
"node_modules/@types/istanbul-lib-report": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz",
"integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==",
"license": "MIT",
"dependencies": {
"@types/istanbul-lib-coverage": "*"
}
},
"node_modules/@types/istanbul-reports": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz",
"integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==",
"license": "MIT",
"dependencies": {
"@types/istanbul-lib-report": "*"
}
},
"node_modules/@types/node": {
"version": "26.4.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz",
"integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/@types/yargs": {
"version": "17.0.35",
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
"integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==",
"license": "MIT",
"dependencies": {
"@types/yargs-parser": "*"
}
},
"node_modules/@types/yargs-parser": {
"version": "21.0.3",
"resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
"license": "MIT"
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/ci-info": {
"version": "3.9.0",
"resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
"integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/sibiraj-s"
}
],
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/jest-mock": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz",
"integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==",
"license": "MIT",
"dependencies": {
"@jest/types": "^29.6.3",
"@types/node": "*",
"jest-util": "^29.7.0"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/jest-util": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz",
"integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==",
"license": "MIT",
"dependencies": {
"@jest/types": "^29.6.3",
"@types/node": "*",
"chalk": "^4.0.0",
"ci-info": "^3.2.0",
"graceful-fs": "^4.2.9",
"picomatch": "^2.2.3"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/picomatch": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"license": "MIT",
"engines": {
"node": ">=8.6"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"license": "MIT"
}
}
}
{
"name": "sample-jest-mock-spy-on",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"jest-mock": "29.7.0"
}
}
{
"schemaVersion": 1,
"goal": "verify jest-mock.spyOn in pkg:npm/jest-mock@29.7.0",
"kind": "HOW",
"packages": [
"pkg:npm/jest-mock@29.7.0"
],
"symbols": [
"jest-mock.spyOn"
]
}
import { spyOn } from "jest-mock";
/**
* Spies on an object method to intercept and track invocations.
*
* @param {object} target - The object containing the method.
* @param {string} methodName - The name of the method to spy on.
* @returns {import("jest-mock").SpiedFunction} The spied function instance.
*/
export function spyMethod(target, methodName) {
return spyOn(target, methodName);
}
/**
* Spies on an object getter property to intercept and track reads.
*
* @param {object} target - The object containing the property.
* @param {string} propName - The name of the property with a getter.
* @returns {import("jest-mock").SpiedGetter} The spied getter instance.
*/
export function spyGetter(target, propName) {
return spyOn(target, propName, "get");
}
/**
* Spies on an object setter property to intercept and track writes.
*
* @param {object} target - The object containing the property.
* @param {string} propName - The name of the property with a setter.
* @returns {import("jest-mock").SpiedSetter} The spied setter instance.
*/
export function spySetter(target, propName) {
return spyOn(target, propName, "set");
}
/**
* Restores a spied method or property accessor to its original state.
*
* @param {import("jest-mock").MockInstance} spy - The spy instance to restore.
*/
export function restoreSpy(spy) {
spy.mockRestore();
}
export { spyOn };
import assert from "node:assert/strict";
import { spyOn } from "jest-mock";
import {
spyMethod,
spyGetter,
spySetter,
restoreSpy
} from "../src/index.mjs";
// 1. spyOn wraps an object method, intercepts invocations, and delegates to the original implementation while recording calls and results
{
const target = {
calculate(a, b) {
return a + b;
}
};
const spy = spyMethod(target, "calculate");
assert.equal(typeof spy, "function");
assert.equal(spy._isMockFunction, true);
assert.equal(spy.mock.calls.length, 0);
const result = target.calculate(10, 20);
assert.equal(result, 30);
assert.equal(spy.mock.calls.length, 1);
assert.deepEqual(spy.mock.calls[0], [10, 20]);
assert.equal(spy.mock.results[0].type, "return");
assert.equal(spy.mock.results[0].value, 30);
restoreSpy(spy);
}
// 2. spyOn mockImplementation replaces method execution logic dynamically while continuing call tracking
{
const greeter = {
greet(name) {
return `Hello, ${name}!`;
}
};
const spy = spyMethod(greeter, "greet");
spy.mockImplementation((name) => `Greetings, ${name}.`);
const output = greeter.greet("Alice");
assert.equal(output, "Greetings, Alice.");
assert.deepEqual(spy.mock.calls, [["Alice"]]);
assert.equal(spy.mock.results[0].type, "return");
assert.equal(spy.mock.results[0].value, "Greetings, Alice.");
restoreSpy(spy);
assert.equal(greeter.greet("Alice"), "Hello, Alice!");
}
// 3. spyOn mockReturnValue and mockReturnValueOnce provide default and one-time return values
{
const dice = {
roll() {
return 1;
}
};
const spy = spyMethod(dice, "roll");
spy.mockReturnValue(100);
spy.mockReturnValueOnce(50);
spy.mockReturnValueOnce(75);
assert.equal(dice.roll(), 50);
assert.equal(dice.roll(), 75);
assert.equal(dice.roll(), 100);
assert.equal(dice.roll(), 100);
restoreSpy(spy);
assert.equal(dice.roll(), 1);
}
// 4. spyOn mockResolvedValue and mockResolvedValueOnce handle asynchronous method resolutions
{
const api = {
async fetchUser(id) {
return { id, name: "real-user" };
}
};
const spy = spyMethod(api, "fetchUser");
spy.mockResolvedValue({ id: 99, name: "fallback-mock" });
spy.mockResolvedValueOnce({ id: 1, name: "first-mock" });
const first = await api.fetchUser(1);
assert.deepEqual(first, { id: 1, name: "first-mock" });
const second = await api.fetchUser(2);
assert.deepEqual(second, { id: 99, name: "fallback-mock" });
restoreSpy(spy);
const real = await api.fetchUser(42);
assert.deepEqual(real, { id: 42, name: "real-user" });
}
// 5. spyOn supports getter and setter property accessors with 'get' and 'set' accessType
{
const config = {
_mode: "development",
get mode() {
return this._mode;
},
set mode(val) {
this._mode = val;
}
};
const getSpy = spyGetter(config, "mode");
assert.equal(config.mode, "development");
assert.equal(getSpy.mock.calls.length, 1);
getSpy.mockReturnValue("production");
assert.equal(config.mode, "production");
restoreSpy(getSpy);
assert.equal(config.mode, "development");
const setSpy = spySetter(config, "mode");
config.mode = "staging";
assert.deepEqual(setSpy.mock.calls, [["staging"]]);
assert.equal(config._mode, "staging");
restoreSpy(setSpy);
config.mode = "test";
assert.equal(config._mode, "test");
}
// 6. spyOn mockRestore restores original method and resets spy call state
{
const target = {
ping() {
return "pong";
}
};
const spy = spyMethod(target, "ping");
spy.mockReturnValue("intercepted");
assert.equal(target.ping(), "intercepted");
assert.equal(spy.mock.calls.length, 1);
restoreSpy(spy);
assert.equal(target.ping(), "pong");
assert.equal(spy.mock.calls.length, 0);
assert.equal(target.ping(), "pong");
assert.equal(spy.mock.calls.length, 0);
}
// 7. spyOn mockClear and mockReset manage recorded invocations and mock implementation state
{
const worker = {
process(item) {
return item * 2;
}
};
const spy = spyMethod(worker, "process");
spy.mockImplementation((item) => item + 10);
assert.equal(worker.process(5), 15);
assert.equal(spy.mock.calls.length, 1);
spy.mockClear();
assert.equal(spy.mock.calls.length, 0);
assert.equal(spy.mock.results.length, 0);
assert.equal(worker.process(5), 15);
assert.equal(spy.mock.calls.length, 1);
spy.mockReset();
assert.equal(spy.mock.calls.length, 0);
assert.equal(worker.process(5), undefined);
assert.equal(spy.mock.calls.length, 1);
restoreSpy(spy);
assert.equal(worker.process(5), 10);
}
console.log("All jest-mock.spyOn contract assertions passed.");
Исходный сидер
аноним