CodeSampleX

示例

jest-mock 29.7.0: replace and restore object properties with jest-mock replaceProperty

已验证示例 — npm jest-mock 29.7.0: replace and restore object properties with jest-mock replaceProperty. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:81ef022695ca27bf8660da205305c954d01a01485b5be95adf3be2c236275f9f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-28

案例

HOW
目标
replace and restore object properties with jest-mock replaceProperty
包
符号
  • ModuleMocker
  • replaceProperty
环境
node 22.23.2
创建时间
2026-08-28T03:11:41Z

契约

  1. replaceProperty replaces an existing configurable property on an object with a new value
  2. replaceProperty handle replaceValue updates the property to subsequent values
  3. replaceProperty handle restore reverts the property to its original value and descriptor
  4. replaceProperty throws descriptive errors for non-existent properties, non-configurable properties, or getters
  5. ModuleMocker replaceProperty tracks replaced properties and restoreAllMocks restores all replaced properties

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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: replace and restore object properties with jest-mock replaceProperty
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jest-mock@29.7.0
Demonstrate these symbols/APIs:
  - ModuleMocker
  - replaceProperty

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:961cf57a2504fa301ce6621cf049b73a890748b6f0c418aef30846857ed1a1a3","contract":["replaceProperty replaces an existing configurable property on an object with a new value","replaceProperty handle replaceValue updates the property to subsequent values","replaceProperty handle restore reverts the property to its original value and descriptor","replaceProperty throws descriptive errors for non-existent properties, non-configurable properties, or getters","ModuleMocker replaceProperty tracks replaced properties and restoreAllMocks restores all replaced properties"],"goal":"replace and restore object properties with jest-mock replaceProperty","kind":"HOW","packages":["pkg:npm/jest-mock@29.7.0"],"schemaVersion":1,"symbols":["ModuleMocker","replaceProperty"]},"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":["ModuleMocker","replaceProperty"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jest-mock-replace-property",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-mock-replace-property",
      "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.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
      "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
      "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"
    }
  }
}
package.json
{
  "name": "sample-jest-mock-replace-property",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "jest-mock": "29.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "replace and restore object properties with jest-mock replaceProperty",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jest-mock@29.7.0"
  ],
  "symbols": [
    "ModuleMocker",
    "replaceProperty"
  ]
}
src/index.mjs
import { replaceProperty, ModuleMocker } from "jest-mock";

/**
 * Replaces a property on an object with a given replacement value.
 * Returns a handle that can be used to further update or restore the property.
 */
export function replaceObjectProperty(target, propertyName, replacementValue) {
  return replaceProperty(target, propertyName, replacementValue);
}

/**
 * Updates a replaced property to a new value using its handle.
 */
export function updateReplacedProperty(handle, nextValue) {
  return handle.replaceValue(nextValue);
}

/**
 * Restores a replaced property back to its original descriptor and value.
 */
export function restoreObjectProperty(handle) {
  return handle.restore();
}

/**
 * Creates a ModuleMocker instance managing mocks and property replacements.
 */
export function createMockerManager(globalObject = globalThis) {
  return new ModuleMocker(globalObject);
}

/**
 * Replaces multiple properties on a target object using a ModuleMocker instance.
 */
export function replacePropertiesWithMocker(mocker, target, propertyMap) {
  const handles = {};
  for (const [key, value] of Object.entries(propertyMap)) {
    handles[key] = mocker.replaceProperty(target, key, value);
  }
  return handles;
}

/**
 * Restores all replaced properties and mocks tracked by a ModuleMocker instance.
 */
export function restoreAllMockerProperties(mocker) {
  return mocker.restoreAllMocks();
}
test/contract.mjs
import assert from "node:assert/strict";
import { replaceProperty, ModuleMocker } from "jest-mock";
import {
  replaceObjectProperty,
  updateReplacedProperty,
  restoreObjectProperty,
  createMockerManager,
  replacePropertiesWithMocker,
  restoreAllMockerProperties
} from "../src/index.mjs";

// Test 1: replaceProperty replaces an existing configurable property on an object with a new value
{
  const target = {
    endpoint: "https://example.com/api/v1",
    timeoutMs: 5000
  };

  const handle = replaceObjectProperty(target, "endpoint", "https://localhost:8080/api/v1");

  assert.equal(target.endpoint, "https://localhost:8080/api/v1");
  assert.equal(target.timeoutMs, 5000);
  assert.equal(typeof handle.replaceValue, "function");
  assert.equal(typeof handle.restore, "function");
}

// Test 2: replaceProperty handle replaceValue updates the property to subsequent values
{
  const settings = { maxRetries: 3 };
  const handle = replaceProperty(settings, "maxRetries", 10);

  assert.equal(settings.maxRetries, 10);

  updateReplacedProperty(handle, 20);
  assert.equal(settings.maxRetries, 20);

  handle.replaceValue(0);
  assert.equal(settings.maxRetries, 0);

  handle.restore();
  assert.equal(settings.maxRetries, 3);
}

// Test 3: replaceProperty handle restore reverts the property to its original value and descriptor
{
  const service = {
    mode: "production",
    version: 1
  };

  const originalDesc = Object.getOwnPropertyDescriptor(service, "mode");
  const handle = replaceObjectProperty(service, "mode", "staging");

  assert.equal(service.mode, "staging");

  restoreObjectProperty(handle);
  assert.equal(service.mode, "production");

  const restoredDesc = Object.getOwnPropertyDescriptor(service, "mode");
  assert.deepEqual(restoredDesc, originalDesc);
}

// Test 4: replaceProperty throws descriptive errors for non-existent properties, non-configurable properties, or getters
{
  const config = {};
  Object.defineProperty(config, "readOnlyFixed", {
    value: "fixed",
    configurable: false,
    writable: false
  });
  Object.defineProperty(config, "computedProp", {
    get() {
      return "computed";
    },
    configurable: true
  });

  // Non-existent property
  assert.throws(
    () => replaceProperty(config, "missingProperty", "value"),
    /Property `missingProperty` does not exist in the provided object/
  );

  // Non-configurable property
  assert.throws(
    () => replaceProperty(config, "readOnlyFixed", "updated"),
    /Property `readOnlyFixed` is not declared configurable/
  );

  // Getter property
  assert.throws(
    () => replaceProperty(config, "computedProp", "override"),
    /Cannot replace the `computedProp` property because it has a getter/
  );

  // Primitive target
  assert.throws(
    () => replaceProperty("not-an-object", "prop", "val"),
    /Cannot use replaceProperty on a primitive value/
  );
}

// Test 5: ModuleMocker replaceProperty tracks replaced properties and restoreAllMocks restores all replaced properties
{
  const mocker = createMockerManager();
  const environment = {
    featureFlagA: false,
    featureFlagB: false,
    concurrency: 1
  };

  replacePropertiesWithMocker(mocker, environment, {
    featureFlagA: true,
    featureFlagB: true,
    concurrency: 8
  });

  assert.equal(environment.featureFlagA, true);
  assert.equal(environment.featureFlagB, true);
  assert.equal(environment.concurrency, 8);

  restoreAllMockerProperties(mocker);

  assert.equal(environment.featureFlagA, false);
  assert.equal(environment.featureFlagB, false);
  assert.equal(environment.concurrency, 1);
}

console.log("All jest-mock replaceProperty contract assertions passed successfully.");

原始种子者

匿名