CodeSampleX

サンプル

@vitest/mocker 3.2.7: ManualMockedModule

検証済みサンプル — npm @vitest/mocker 3.2.7: ManualMockedModule. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: ManualMockedModule instantiates with raw…

sha256:3f34f60435423a5e212825cdf75c673f41391eff1f22a06564a42798c75a68fb

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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.ManualMockedModule in pkg:npm/%40vitest/mocker@3.2.7
パッケージ
シンボル
  • @vitest/mocker.ManualMockedModule
環境
node 22.23.2
作成日
2026-08-23T14:50:13Z

コントラクト

  1. ManualMockedModule instantiates with raw specifier, id, url, and factory function
  2. ManualMockedModule.resolve executes factory and caches the returned exports object
  3. ManualMockedModule.resolve returns cached exports on subsequent calls without re-invoking factory
  4. ManualMockedModule.resolve supports async factory functions
  5. ManualMockedModule.toJSON serializes module metadata without factory
  6. ManualMockedModule.fromJSON reconstructs ManualMockedModule instance from serialized data and factory
  7. ManualMockedModule.resolve throws TypeError if factory returns non-object value
  8. ManualMockedModule.resolve wraps factory runtime errors with vitest error message and cause

ファイル

  • PROMPT.md
  • csx.json
  • 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 @vitest/mocker.ManualMockedModule 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.ManualMockedModule

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:bba8b38735a4cb5c01a4cc70abeac8528a2d75a9e285b0ab7ae9cfdad0d7c5fd","contract":["ManualMockedModule instantiates with raw specifier, id, url, and factory function","ManualMockedModule.resolve executes factory and caches the returned exports object","ManualMockedModule.resolve returns cached exports on subsequent calls without re-invoking factory","ManualMockedModule.resolve supports async factory functions","ManualMockedModule.toJSON serializes module metadata without factory","ManualMockedModule.fromJSON reconstructs ManualMockedModule instance from serialized data and factory","ManualMockedModule.resolve throws TypeError if factory returns non-object value","ManualMockedModule.resolve wraps factory runtime errors with vitest error message and cause"],"goal":"verify @vitest/mocker.ManualMockedModule in pkg:npm/%40vitest/mocker@3.2.7","kind":"HOW","packages":["pkg:npm/%40vitest/mocker@3.2.7"],"schemaVersion":1,"symbols":["@vitest/mocker.ManualMockedModule"]},"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/%40vitest/mocker@3.2.7"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/mocker@3.2.7","symbols":["@vitest/mocker.ManualMockedModule"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-vitest-mocker-manualmockedmodule",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-mocker-manualmockedmodule",
      "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"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-mocker-manualmockedmodule",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "description": "Clean-room verification for @vitest/mocker.ManualMockedModule in @vitest/mocker@3.2.7",
  "main": "test/contract.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/mocker": "3.2.7"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/mocker.ManualMockedModule in pkg:npm/%40vitest/mocker@3.2.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/mocker@3.2.7"
  ],
  "symbols": [
    "@vitest/mocker.ManualMockedModule"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import { ManualMockedModule } from '@vitest/mocker';

async function runContract() {
  // 1. Instantiation with raw specifier, id, url, and factory function
  const factory1 = () => ({ foo: 'bar', version: 1 });
  const mock1 = new ManualMockedModule('example-module', '/path/to/example-module', 'file:///path/to/example-module', factory1);

  assert.strictEqual(mock1.type, 'manual', 'mock1.type should be "manual"');
  assert.strictEqual(mock1.raw, 'example-module', 'mock1.raw should match raw specifier');
  assert.strictEqual(mock1.id, '/path/to/example-module', 'mock1.id should match id');
  assert.strictEqual(mock1.url, 'file:///path/to/example-module', 'mock1.url should match url');
  assert.strictEqual(mock1.factory, factory1, 'mock1.factory should reference the factory function');
  assert.strictEqual(mock1.cache, undefined, 'mock1.cache should be undefined prior to resolution');

  // 2. resolve() executes factory and caches the returned exports object
  const resolved1 = await mock1.resolve();
  assert.deepStrictEqual(resolved1, { foo: 'bar', version: 1 }, 'resolved exports should match factory output');
  assert.strictEqual(mock1.cache, resolved1, 'mock1.cache should store resolved exports');

  // 3. Subsequent resolve() calls return cached exports without re-invoking factory
  let executionCount = 0;
  const mockCached = new ManualMockedModule('calc-service', '/path/to/calc', 'file:///path/to/calc', () => {
    executionCount++;
    return { count: executionCount };
  });

  const firstResolution = await mockCached.resolve();
  const secondResolution = await mockCached.resolve();
  assert.strictEqual(executionCount, 1, 'factory should execute exactly once');
  assert.strictEqual(firstResolution, secondResolution, 'subsequent resolutions should return identical cache reference');
  assert.strictEqual(secondResolution.count, 1, 'cached value should be preserved');

  // 4. resolve() supports async factory functions
  const mockAsync = new ManualMockedModule('async-service', '/path/to/async', 'file:///path/to/async', async () => {
    return { data: 'async-result' };
  });
  const asyncResult = await mockAsync.resolve();
  assert.deepStrictEqual(asyncResult, { data: 'async-result' }, 'async factory result should be resolved');

  // 5. toJSON() serializes module metadata without factory
  const serialized = mock1.toJSON();
  assert.deepStrictEqual(
    serialized,
    {
      type: 'manual',
      url: 'file:///path/to/example-module',
      id: '/path/to/example-module',
      raw: 'example-module'
    },
    'toJSON should produce expected serializable metadata'
  );

  // 6. fromJSON() reconstructs ManualMockedModule instance from serialized data and factory
  const factoryReconstructed = () => ({ restored: true });
  const reconstructedMock = ManualMockedModule.fromJSON(serialized, factoryReconstructed);
  assert.strictEqual(reconstructedMock instanceof ManualMockedModule, true, 'reconstructed instance should be ManualMockedModule');
  assert.strictEqual(reconstructedMock.type, 'manual');
  assert.strictEqual(reconstructedMock.raw, 'example-module');
  assert.strictEqual(reconstructedMock.id, '/path/to/example-module');
  assert.strictEqual(reconstructedMock.url, 'file:///path/to/example-module');
  const reconstructedResult = await reconstructedMock.resolve();
  assert.deepStrictEqual(reconstructedResult, { restored: true }, 'reconstructed mock should resolve using supplied factory');

  // 7. resolve() throws TypeError if factory returns non-object value
  const invalidMock = new ManualMockedModule('invalid-module', '/invalid', 'file:///invalid', () => 'not an object');
  await assert.rejects(
    async () => {
      await invalidMock.resolve();
    },
    (err) => {
      assert.strictEqual(err instanceof TypeError, true, 'err should be TypeError');
      assert.ok(err.message.includes('is not returning an object'), 'error message should describe non-object return');
      return true;
    }
  );

  // 8. resolve() wraps factory runtime errors with vitest error message and cause
  const throwingMock = new ManualMockedModule('throwing-module', '/throw', 'file:///throw', () => {
    throw new Error('underlying factory error');
  });
  await assert.rejects(
    async () => {
      await throwingMock.resolve();
    },
    (err) => {
      assert.ok(err.message.includes('[vitest] There was an error when mocking a module'), 'error message should include vitest prefix');
      assert.ok(err.cause instanceof Error, 'err.cause should contain original error');
      assert.strictEqual(err.cause.message, 'underlying factory error');
      return true;
    }
  );

  console.log('Contract tests passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

オリジンシーダー

匿名