示例
jest-mock 29.7.0: mock function creation and call tracking with jest-mock
已验证示例 — npm jest-mock 29.7.0: mock function creation and call tracking with jest-mock. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.
sha256:10c294a7da2d5f2c2b79def6fdffa04589c2f7b1f9269c1217cd3c50e04b95b3
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
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- 目标
- mock function creation and call tracking with jest-mock
- 符号
-
- fn
- spyOn
- 环境
- node 22.23.2
- 创建时间
- 2026-08-26T06:43:40Z
契约
- fn creates a callable mock function tracking arguments and return values in mock.calls and mock.results
- fn mockReturnValue and mockReturnValueOnce support default and sequential return values
- fn mockImplementation overrides execution logic dynamically
- spyOn wraps an existing object method to intercept and record invocations without altering default behavior
- spyOn mockImplementation temporarily overrides method behavior and mockRestore restores original implementation
文件
- 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: mock function creation and call tracking with jest-mock
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jest-mock@29.7.0
Demonstrate these symbols/APIs:
- fn
- 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:b62367dc814c2716e2197988a049dd60f4ca63c5d7405a8be18501c816e7d5ad","contract":["fn creates a callable mock function tracking arguments and return values in mock.calls and mock.results","fn mockReturnValue and mockReturnValueOnce support default and sequential return values","fn mockImplementation overrides execution logic dynamically","spyOn wraps an existing object method to intercept and record invocations without altering default behavior","spyOn mockImplementation temporarily overrides method behavior and mockRestore restores original implementation"],"goal":"mock function creation and call tracking with jest-mock","kind":"HOW","packages":["pkg:npm/jest-mock@29.7.0"],"schemaVersion":1,"symbols":["fn","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":["fn","spyOn"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-jest-mock",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-jest-mock",
"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.3.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.3.0.tgz",
"integrity": "sha512-L3fgrnchriRC2ExBflb8j4uZZURHZfQsmQeyVzhjcHW4kkwVyo8/0h1B2MVzMTrYUJYu6G7EWs14hW/L9putqw==",
"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",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"jest-mock": "29.7.0"
}
}
{
"schemaVersion": 1,
"goal": "mock function creation and call tracking with jest-mock",
"kind": "HOW",
"packages": [
"pkg:npm/jest-mock@29.7.0"
],
"symbols": [
"fn",
"spyOn"
]
}
import { fn, spyOn } from "jest-mock";
/**
* Creates a mock function that tracks invocations and return values.
*/
export function createTrackedHandler(implementation) {
return implementation ? fn(implementation) : fn();
}
/**
* Creates a stub function that returns predefined sequential values followed by a default.
*/
export function createSequenceStub(sequence, fallbackValue) {
const mockFunc = fn();
for (const item of sequence) {
mockFunc.mockReturnValueOnce(item);
}
if (fallbackValue !== undefined) {
mockFunc.mockReturnValue(fallbackValue);
}
return mockFunc;
}
/**
* Attaches a spy to an object method to observe invocations.
*/
export function attachMethodSpy(target, methodName) {
return spyOn(target, methodName);
}
/**
* Attaches a spy to an object method and substitutes custom implementation.
*/
export function attachCustomImplementationSpy(target, methodName, implementation) {
const spy = spyOn(target, methodName);
spy.mockImplementation(implementation);
return spy;
}
/**
* Restores a spy to the original target method implementation.
*/
export function restoreMethodSpy(spy) {
spy.mockRestore();
}
/**
* Retrieves the recorded call history and results from a mock or spy.
*/
export function getMockCallSummary(mockOrSpy) {
return {
callCount: mockOrSpy.mock.calls.length,
calls: mockOrSpy.mock.calls,
results: mockOrSpy.mock.results.map(r => r.value)
};
}
import assert from "node:assert/strict";
import { fn, spyOn } from "jest-mock";
import {
createTrackedHandler,
createSequenceStub,
attachMethodSpy,
attachCustomImplementationSpy,
restoreMethodSpy,
getMockCallSummary
} from "../src/index.mjs";
// Test 1: fn creates a callable mock function tracking arguments and return values in mock.calls and mock.results
{
const handler = createTrackedHandler((x, y) => x + y);
assert.equal(typeof handler, "function");
assert.equal(handler.mock.calls.length, 0);
const res1 = handler(10, 20);
const res2 = handler(5, 15);
assert.equal(res1, 30);
assert.equal(res2, 20);
const summary = getMockCallSummary(handler);
assert.equal(summary.callCount, 2);
assert.deepEqual(summary.calls, [[10, 20], [5, 15]]);
assert.deepEqual(summary.results, [30, 20]);
assert.equal(handler.mock.results[0].type, "return");
assert.equal(handler.mock.results[0].value, 30);
assert.equal(handler.mock.results[1].type, "return");
assert.equal(handler.mock.results[1].value, 20);
}
// Test 2: fn mockReturnValue and mockReturnValueOnce support default and sequential return values
{
const stub = createSequenceStub(["first", "second"], "fallback");
assert.equal(stub(), "first");
assert.equal(stub(), "second");
assert.equal(stub(), "fallback");
assert.equal(stub(), "fallback");
assert.equal(stub.mock.calls.length, 4);
// Direct fn test for mockReturnValue
const defaultMock = fn().mockReturnValue(42);
assert.equal(defaultMock(), 42);
assert.equal(defaultMock(), 42);
}
// Test 3: fn mockImplementation overrides execution logic dynamically
{
const operation = fn((val) => val * 2);
assert.equal(operation(5), 10);
operation.mockImplementation((val) => val * 10);
assert.equal(operation(5), 50);
operation.mockImplementationOnce((val) => `custom:${val}`);
assert.equal(operation(5), "custom:5");
assert.equal(operation(5), 50);
}
// Test 4: spyOn wraps an existing object method to intercept and record invocations without altering default behavior
{
const calculator = {
multiplier: 3,
multiply(a, b) {
return a * b * this.multiplier;
}
};
const spy = attachMethodSpy(calculator, "multiply");
assert.equal(spy.mock.calls.length, 0);
const result = calculator.multiply(2, 4);
assert.equal(result, 24); // original behavior preserved with context
assert.equal(spy.mock.calls.length, 1);
assert.deepEqual(spy.mock.calls[0], [2, 4]);
assert.equal(spy.mock.results[0].value, 24);
restoreMethodSpy(spy);
}
// Test 5: spyOn mockImplementation temporarily overrides method behavior and mockRestore restores original implementation
{
const greeter = {
greet(name) {
return `Hello, ${name}!`;
}
};
assert.equal(greeter.greet("Alice"), "Hello, Alice!");
const spy = attachCustomImplementationSpy(greeter, "greet", (name) => `Hi, ${name}.`);
assert.equal(greeter.greet("Alice"), "Hi, Alice.");
assert.equal(spy.mock.calls.length, 1);
assert.deepEqual(spy.mock.calls[0], ["Alice"]);
restoreMethodSpy(spy);
assert.equal(greeter.greet("Alice"), "Hello, Alice!");
}
console.log("All jest-mock contract assertions passed successfully.");
原始种子者
匿名