示例
@vitest/mocker 3.2.7: mockObject
已验证示例 — npm @vitest/mocker 3.2.7: mockObject. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: mockObject is a function exported by @vitest/mocker
sha256:78d430a51ebb2df137d1f1dc90de0acf38801d04e567667a62a488c2b2aba309
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 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-23 |
案例
HOW- 目标
- verify @vitest/mocker.mockObject in pkg:npm/%40vitest/mocker@3.2.7
- 符号
-
- @vitest/mocker.mockObject
- 环境
- node 22.23.2
- 创建时间
- 2026-08-23T14:31:47Z
契约
- mockObject is a function exported by @vitest/mocker
- mockObject preserves primitive properties including numbers, strings, and booleans
- mockObject automocks function properties into spy wrappers returning undefined by default
- mockObject initializes array properties to empty arrays
- mockObject recursively mocks nested object hierarchies
- mockObject resolves circular object references without infinite loops
- mockObject preserves property getters on non-module objects
- mockObject populates custom target mockExports container when provided
- mockObject wraps class constructors and spies on instantiated methods
- mockObject integrates with custom spyOn factory supporting mockReturnValue and mockImplementation
- createMockObject and createSimpleSpyFactory helpers wrap mockObject with standard defaults
文件
- 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 @vitest/mocker.mockObject in pkg:npm/%40vitest/mocker@3.2.7
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/%40vitest/mocker@3.2.7
Demonstrate these symbols/APIs:
- @vitest/mocker.mockObject
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.
{"case":{"caseId":"case:sha256:40e62251d6a655fc554ee8b84d9cc89ad09fdf2d07e9e987e621e6493ebf8403","constraints":{"executionContext":"node"},"contract":["mockObject is a function exported by @vitest/mocker","mockObject preserves primitive properties including numbers, strings, and booleans","mockObject automocks function properties into spy wrappers returning undefined by default","mockObject initializes array properties to empty arrays","mockObject recursively mocks nested object hierarchies","mockObject resolves circular object references without infinite loops","mockObject preserves property getters on non-module objects","mockObject populates custom target mockExports container when provided","mockObject wraps class constructors and spies on instantiated methods","mockObject integrates with custom spyOn factory supporting mockReturnValue and mockImplementation","createMockObject and createSimpleSpyFactory helpers wrap mockObject with standard defaults"],"goal":"verify @vitest/mocker.mockObject in pkg:npm/%40vitest/mocker@3.2.7","kind":"HOW","packages":["pkg:npm/%40vitest/mocker@3.2.7"],"schemaVersion":1,"symbols":["@vitest/mocker.mockObject"]},"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/%40vitest/mocker@3.2.7"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/mocker@3.2.7","symbols":["@vitest/mocker.mockObject"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-vitest-mocker-mock-object",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-vitest-mocker-mock-object",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"@vitest/mocker": "3.2.7"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
"license": "MIT"
},
"node_modules/@vitest/mocker": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",
"integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",
"license": "MIT",
"dependencies": {
"@vitest/spy": "3.2.7",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.17"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/spy": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",
"integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",
"license": "MIT",
"dependencies": {
"tinyspy": "^4.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/tinyspy": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
"integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
}
}
}
{
"name": "sample-vitest-mocker-mock-object",
"version": "1.0.0",
"private": true,
"description": "Clean-room verification of @vitest/mocker.mockObject in @vitest/mocker@3.2.7",
"main": "src/index.mjs",
"type": "module",
"license": "MIT-0",
"dependencies": {
"@vitest/mocker": "3.2.7"
}
}
{
"schemaVersion": 1,
"goal": "verify @vitest/mocker.mockObject in pkg:npm/%40vitest/mocker@3.2.7",
"kind": "HOW",
"packages": [
"pkg:npm/%40vitest/mocker@3.2.7"
],
"symbols": [
"@vitest/mocker.mockObject"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
import { mockObject } from "@vitest/mocker";
/**
* Returns the standard set of global constructors required by @vitest/mocker.mockObject.
*
* @returns {object} Map of standard global constructors (Object, Function, RegExp, Array, Map).
*/
export function getDefaultGlobalConstructors() {
return {
Object,
Function,
RegExp,
Array,
Map,
};
}
/**
* Creates a minimal spy factory adhering to the mockObject spy contract.
*
* @param {Record<string | symbol, any[]>} [spyCallsRecorder=null] - Optional recorder dictionary for invocations.
* @returns {(container: any, prop: string | symbol) => any} Spy generator conforming to the mockObject protocol.
*/
export function createSimpleSpyFactory(spyCallsRecorder = null) {
return (container, prop) => {
let currentImplementation = null;
const calls = [];
const spy = function (...args) {
calls.push(args);
if (spyCallsRecorder) {
if (!spyCallsRecorder[prop]) {
spyCallsRecorder[prop] = [];
}
spyCallsRecorder[prop].push(args);
}
if (currentImplementation) {
return Reflect.apply(currentImplementation, this, args);
}
return undefined;
};
spy.mock = {
calls,
results: [],
};
spy.mockImplementation = (fn) => {
currentImplementation = fn;
return spy;
};
spy.mockReturnValue = (val) => {
currentImplementation = () => val;
return spy;
};
spy.mockReset = () => {
calls.length = 0;
currentImplementation = null;
return spy;
};
spy.mockRestore = () => {
spy.mockReset();
return spy;
};
container[prop] = spy;
return spy;
};
}
/**
* Convenience helper to mock an object or module structure using @vitest/mocker.mockObject.
*
* @param {Record<string | symbol, any>} target - The source object to mock.
* @param {object} [options={}] - Mock configuration options.
* @param {string} [options.type='automock'] - Mock type ('automock', 'autospy', 'manual', 'redirect').
* @param {Function} [options.spyOn] - Custom spy factory function.
* @param {object} [options.globalConstructors] - Map of constructors.
* @param {Record<string | symbol, any>} [mockExports={}] - Target exports object to populate.
* @returns {Record<string | symbol, any>} The resulting mocked object.
*/
export function createMockObject(target, options = {}, mockExports = {}) {
const spyOn = options.spyOn || createSimpleSpyFactory();
const globalConstructors = options.globalConstructors || getDefaultGlobalConstructors();
const type = options.type || "automock";
return mockObject(
{
type,
globalConstructors,
spyOn,
},
target,
mockExports
);
}
export { mockObject };
export default mockObject;
import assert from "node:assert/strict";
import { mockObject } from "@vitest/mocker";
import {
createMockObject,
createSimpleSpyFactory,
getDefaultGlobalConstructors,
} from "../src/index.mjs";
const constructors = getDefaultGlobalConstructors();
// 1. mockObject is a function exported by @vitest/mocker
{
assert.strictEqual(typeof mockObject, "function", "mockObject must be a function");
}
// 2. mockObject preserves primitive properties including numbers, strings, and booleans
{
const source = {
numeric: 123,
text: "vitest-mocker",
flag: true,
nil: null,
};
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
source
);
assert.strictEqual(mocked.numeric, 123);
assert.strictEqual(mocked.text, "vitest-mocker");
assert.strictEqual(mocked.flag, true);
assert.strictEqual(mocked.nil, null);
}
// 3. mockObject automocks function properties into spy wrappers returning undefined by default
{
const recorder = {};
const spyOn = createSimpleSpyFactory(recorder);
const source = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
},
};
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn,
},
source
);
assert.strictEqual(typeof mocked.add, "function");
assert.strictEqual(typeof mocked.subtract, "function");
assert.strictEqual(mocked.add.length, 0);
const result = mocked.add(10, 20);
assert.strictEqual(result, undefined, "Automocked function returns undefined by default");
assert.strictEqual(recorder.add.length, 1);
assert.deepStrictEqual(recorder.add[0], [10, 20]);
}
// 4. mockObject initializes array properties to empty arrays
{
const source = {
items: [1, 2, 3, "four"],
nested: {
tags: ["alpha", "beta"],
},
};
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
source
);
assert.ok(Array.isArray(mocked.items), "items should be an array");
assert.strictEqual(mocked.items.length, 0, "mocked array should be empty");
assert.ok(Array.isArray(mocked.nested.tags), "nested.tags should be an array");
assert.strictEqual(mocked.nested.tags.length, 0, "nested.tags should be empty");
}
// 5. mockObject recursively mocks nested object hierarchies
{
const source = {
level1: {
level2: {
leafValue: "deep",
leafFn: () => "original-leaf",
},
},
};
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
source
);
assert.strictEqual(mocked.level1.level2.leafValue, "deep");
assert.strictEqual(typeof mocked.level1.level2.leafFn, "function");
assert.strictEqual(mocked.level1.level2.leafFn(), undefined);
}
// 6. mockObject resolves circular object references without infinite loops
{
const parent = {
name: "parent-node",
child: {
name: "child-node",
parentRef: null,
},
};
parent.child.parentRef = parent.child;
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
parent
);
assert.strictEqual(mocked.name, "parent-node");
assert.strictEqual(mocked.child.name, "child-node");
assert.strictEqual(mocked.child.parentRef, mocked.child, "Circular reference must be preserved");
}
// 7. mockObject preserves property getters on non-module objects
{
const source = {
get computed() {
return "dynamic-getter-value";
},
};
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
source
);
assert.strictEqual(mocked.computed, "dynamic-getter-value");
}
// 8. mockObject populates custom target mockExports container when provided
{
const targetExports = {
existingSetting: "keep-me",
};
const source = {
fn: () => 42,
};
const result = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
source,
targetExports
);
assert.strictEqual(result, targetExports, "mockObject should mutate and return the passed mockExports");
assert.strictEqual(result.existingSetting, "keep-me");
assert.strictEqual(typeof result.fn, "function");
}
// 9. mockObject wraps class constructors and spies on instantiated methods
{
class Greeter {
constructor(prefix) {
this.prefix = prefix;
}
sayHello(target) {
return `${this.prefix} ${target}`;
}
}
const mockedModule = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
{ Greeter }
);
const instance = new mockedModule.Greeter("Hello");
assert.strictEqual(typeof instance.sayHello, "function");
const greeting = instance.sayHello("World");
assert.strictEqual(greeting, undefined, "Default automocked instance method returns undefined");
}
// 10. mockObject integrates with custom spyOn factory supporting mockReturnValue and mockImplementation
{
const source = {
calc: (x) => x * 2,
fetch: () => "raw",
};
const mocked = mockObject(
{
type: "automock",
globalConstructors: constructors,
spyOn: createSimpleSpyFactory(),
},
source
);
mocked.calc.mockImplementation((x) => x + 10);
assert.strictEqual(mocked.calc(5), 15);
mocked.fetch.mockReturnValue("mocked-response");
assert.strictEqual(mocked.fetch(), "mocked-response");
}
// 11. createMockObject and createSimpleSpyFactory helpers wrap mockObject with standard defaults
{
const source = {
answer: 42,
compute: () => 100,
};
const mocked = createMockObject(source);
assert.strictEqual(mocked.answer, 42);
assert.strictEqual(typeof mocked.compute, "function");
assert.strictEqual(mocked.compute(), undefined);
}
console.log("All @vitest/mocker.mockObject contract assertions passed successfully.");
原始种子者
匿名