CodeSampleX

示例

@vitest/snapshot 2.1.9: SnapshotClient

已验证示例 — npm @vitest/snapshot 2.1.9: SnapshotClient. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: SnapshotClient initializes with optional…

sha256:e675d7acaf7b80bbca02a74132588fd4edb1898f61d16650811f17d9530a079d

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

案例

HOW
目标
verify SnapshotClient in pkg:npm/%40vitest/snapshot@2.1.9
包
符号
  • SnapshotClient
环境
node 22.23.2
创建时间
2026-08-27T01:53:37Z

契约

  1. SnapshotClient initializes with optional configuration options such as custom isEqual comparator
  2. startCurrentRun initializes SnapshotState for a test file using the provided snapshotEnvironment
  3. getSnapshotState returns the active SnapshotState associated with the test file path
  4. assert records and writes new external snapshots when updateSnapshot is set to new
  5. assert matches existing snapshots and throws mismatch error when received value differs
  6. assert with properties validates received object properties before matching snapshot
  7. assert throws an error when called without an active test file context
  8. assertRaw resolves, writes, and asserts against raw snapshot files on disk
  9. skipTestSnapshots marks skipped test snapshots as checked to prevent unchecked reports
  10. finishCurrentRun packs snapshot summary metrics and clears active test state
  11. clear resets all cached SnapshotState instances in the client map

文件

  • PROMPT.md
  • csx.json
  • index.mjs
  • 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 SnapshotClient in pkg:npm/%40vitest/snapshot@2.1.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/snapshot@2.1.9
Demonstrate these symbols/APIs:
  - SnapshotClient
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.
csx.json
{"case":{"caseId":"case:sha256:0c02af53b1aedae8f94fbdb54157ad734a21e6f1ba57445019046ceee97429da","constraints":{"executionContext":"node"},"contract":["SnapshotClient initializes with optional configuration options such as custom isEqual comparator","startCurrentRun initializes SnapshotState for a test file using the provided snapshotEnvironment","getSnapshotState returns the active SnapshotState associated with the test file path","assert records and writes new external snapshots when updateSnapshot is set to new","assert matches existing snapshots and throws mismatch error when received value differs","assert with properties validates received object properties before matching snapshot","assert throws an error when called without an active test file context","assertRaw resolves, writes, and asserts against raw snapshot files on disk","skipTestSnapshots marks skipped test snapshots as checked to prevent unchecked reports","finishCurrentRun packs snapshot summary metrics and clears active test state","clear resets all cached SnapshotState instances in the client map"],"goal":"verify SnapshotClient in pkg:npm/%40vitest/snapshot@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/snapshot@2.1.9"],"schemaVersion":1,"symbols":["SnapshotClient"]},"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/snapshot@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/snapshot@2.1.9","symbols":["SnapshotClient"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { SnapshotClient, SnapshotState } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';

export {
  SnapshotClient,
  SnapshotState,
  NodeSnapshotEnvironment
};

/**
 * Creates and configures a new SnapshotClient instance.
 *
 * @param {object} [options] - Configuration options such as custom isEqual comparator.
 * @returns {SnapshotClient} Configured SnapshotClient instance.
 */
export function createSnapshotClient(options) {
  return new SnapshotClient(options);
}

/**
 * Executes a full snapshot lifecycle assertion run.
 *
 * @param {SnapshotClient} client - The snapshot client instance.
 * @param {string} testFilePath - The test file path for snapshot association.
 * @param {string} testName - The name of the test or suite.
 * @param {object} runOptions - Options passed to startCurrentRun (snapshotEnvironment, updateSnapshot, etc).
 * @param {Function} assertionFn - Callback receiving the client to perform assertions.
 * @returns {Promise<object>} Result returned by finishCurrentRun.
 */
export async function runSnapshotSession(client, testFilePath, testName, runOptions, assertionFn) {
  await client.startCurrentRun(testFilePath, testName, runOptions);
  await assertionFn(client);
  return await client.finishCurrentRun();
}
package-lock.json
{
  "name": "sample-vitest-snapshot",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-snapshot",
      "version": "1.0.0",
      "dependencies": {
        "@vitest/snapshot": "2.1.9"
      }
    },
    "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/@vitest/pretty-format": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
      "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/snapshot": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
      "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "2.1.9",
        "magic-string": "^0.30.12",
        "pathe": "^1.1.2"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "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/pathe": {
      "version": "1.1.2",
      "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
      "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
      "license": "MIT"
    },
    "node_modules/tinyrainbow": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
      "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-snapshot",
  "version": "1.0.0",
  "description": "Clean-room verification sample for SnapshotClient in @vitest/snapshot",
  "type": "module",
  "main": "index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/snapshot": "2.1.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify SnapshotClient in pkg:npm/%40vitest/snapshot@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/snapshot@2.1.9"
  ],
  "symbols": [
    "SnapshotClient"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import {
  SnapshotClient,
  SnapshotState,
  NodeSnapshotEnvironment,
  createSnapshotClient,
  runSnapshotSession
} from '../index.mjs';

const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'csx-vitest-snapshot-test-'));

try {
  const snapEnv = new NodeSnapshotEnvironment();
  const testFilePath = path.join(tmpDir, 'suite.test.js');

  // 1. SnapshotClient initializes with optional configuration options such as custom isEqual comparator
  const customIsEqual = (received, expected) => {
    for (const key of Object.keys(expected)) {
      if (typeof expected[key] === 'function') {
        if (!expected[key](received[key])) return false;
      } else if (received[key] !== expected[key]) {
        return false;
      }
    }
    return true;
  };

  const client = createSnapshotClient({ isEqual: customIsEqual });
  assert.ok(client instanceof SnapshotClient);
  assert.strictEqual(client.options.isEqual, customIsEqual);

  // 2. startCurrentRun initializes SnapshotState for a test file using the provided snapshotEnvironment
  await client.startCurrentRun(testFilePath, 'sample test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'new'
  });

  assert.strictEqual(client.filepath, testFilePath);
  assert.strictEqual(client.name, 'sample test');

  // 3. getSnapshotState returns the active SnapshotState associated with the test file path
  const state = client.getSnapshotState(testFilePath);
  assert.ok(state instanceof SnapshotState);
  assert.strictEqual(state.testFilePath, testFilePath);

  // 4. assert records and writes new external snapshots when updateSnapshot is set to new
  client.assert({
    received: {
      status: 'success',
      data: [10, 20, 30]
    },
    isInline: false
  });

  const packResult1 = await client.finishCurrentRun();
  assert.deepStrictEqual(packResult1, {
    filepath: testFilePath,
    added: 1,
    fileDeleted: false,
    matched: 0,
    unchecked: 0,
    uncheckedKeys: [],
    unmatched: 0,
    updated: 0
  });

  const snapFilePath = await snapEnv.resolvePath(testFilePath);
  assert.ok(fs.existsSync(snapFilePath), 'Snapshot file should be written to disk');
  const snapContent = fs.readFileSync(snapFilePath, 'utf8');
  assert.ok(snapContent.includes('exports[`sample test 1`] ='));
  assert.ok(snapContent.includes('"status": "success"'));

  // 5. assert matches existing snapshots and throws mismatch error when received value differs
  client.clear();
  await client.startCurrentRun(testFilePath, 'sample test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'none'
  });

  // Successful match
  client.assert({
    received: {
      status: 'success',
      data: [10, 20, 30]
    },
    isInline: false
  });

  const packResult2 = await client.finishCurrentRun();
  assert.strictEqual(packResult2.matched, 1);
  assert.strictEqual(packResult2.unmatched, 0);

  // Mismatch error thrown on differing value
  client.clear();
  await client.startCurrentRun(testFilePath, 'sample test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'none'
  });

  assert.throws(
    () => {
      client.assert({
        received: {
          status: 'error',
          data: [10, 20, 30]
        },
        isInline: false
      });
    },
    /Snapshot `sample test 1` mismatched/
  );

  const packResult3 = await client.finishCurrentRun();
  assert.strictEqual(packResult3.unmatched, 1);

  // 6. assert with properties validates received object properties before matching snapshot
  const propTestFilePath = path.join(tmpDir, 'prop.test.js');
  const isString = (v) => typeof v === 'string';
  const isNumber = (v) => typeof v === 'number';

  const propClient = createSnapshotClient({ isEqual: customIsEqual });
  await propClient.startCurrentRun(propTestFilePath, 'property match test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'new'
  });

  propClient.assert({
    received: { id: 'evt_101', timestamp: 1718000000, type: 'click' },
    properties: { id: isString, timestamp: isNumber },
    isInline: false
  });

  const propPack1 = await propClient.finishCurrentRun();
  assert.strictEqual(propPack1.added, 1);

  // Match with new values satisfying property predicates
  propClient.clear();
  await propClient.startCurrentRun(propTestFilePath, 'property match test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'none'
  });

  propClient.assert({
    received: { id: 'evt_999', timestamp: 1718999999, type: 'click' },
    properties: { id: isString, timestamp: isNumber },
    isInline: false
  });

  const propPack2 = await propClient.finishCurrentRun();
  assert.strictEqual(propPack2.matched, 1);

  // Rejects when property validation predicate fails
  propClient.clear();
  await propClient.startCurrentRun(propTestFilePath, 'property match test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'none'
  });

  assert.throws(
    () => {
      propClient.assert({
        received: { id: 12345, timestamp: 'invalid_ts', type: 'click' },
        properties: { id: isString, timestamp: isNumber },
        isInline: false
      });
    },
    /Snapshot mismatched/
  );

  await propClient.finishCurrentRun();

  // 7. assert throws an error when called without an active test file context
  const detachedClient = createSnapshotClient();
  assert.throws(
    () => {
      detachedClient.assert({ received: 'orphan value' });
    },
    /Snapshot cannot be used outside of test/
  );

  // 8. assertRaw resolves, writes, and asserts against raw snapshot files on disk
  const rawTestFilePath = path.join(tmpDir, 'raw.test.js');
  const rawTargetFile = path.join(tmpDir, 'output.raw.txt');
  const rawClient = createSnapshotClient();

  await rawClient.startCurrentRun(rawTestFilePath, 'raw snapshot test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'new'
  });

  await rawClient.assertRaw({
    received: 'RAW_DOCUMENT_BODY_CONTENT_12345\n',
    rawSnapshot: {
      file: rawTargetFile
    }
  });

  const rawPack1 = await rawClient.finishCurrentRun();
  assert.strictEqual(rawPack1.added, 1);
  assert.ok(fs.existsSync(rawTargetFile));
  assert.strictEqual(fs.readFileSync(rawTargetFile, 'utf8'), 'RAW_DOCUMENT_BODY_CONTENT_12345\n');

  // Verify assertRaw matches saved content
  rawClient.clear();
  await rawClient.startCurrentRun(rawTestFilePath, 'raw snapshot test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'none'
  });

  await rawClient.assertRaw({
    received: 'RAW_DOCUMENT_BODY_CONTENT_12345\n',
    rawSnapshot: {
      file: rawTargetFile
    }
  });

  const rawPack2 = await rawClient.finishCurrentRun();
  assert.strictEqual(rawPack2.matched, 1);

  // 9. skipTestSnapshots marks skipped test snapshots as checked to prevent unchecked reports
  const skipTestFilePath = path.join(tmpDir, 'skip.test.js');
  const skipClient = createSnapshotClient();

  await skipClient.startCurrentRun(skipTestFilePath, 'active-test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'new'
  });
  skipClient.assert({ received: 'active value' });
  await skipClient.finishCurrentRun();

  skipClient.clear();
  await skipClient.startCurrentRun(skipTestFilePath, 'skipped-test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'new'
  });
  skipClient.assert({ received: 'skipped value' });
  await skipClient.finishCurrentRun();

  // Next run: only execute active-test and mark skipped-test as skipped
  skipClient.clear();
  await skipClient.startCurrentRun(skipTestFilePath, 'active-test', {
    snapshotEnvironment: snapEnv,
    updateSnapshot: 'none'
  });
  skipClient.assert({ received: 'active value' });
  skipClient.skipTestSnapshots('skipped-test');

  const skipPack = await skipClient.finishCurrentRun();
  assert.strictEqual(skipPack.matched, 1);
  assert.strictEqual(skipPack.unchecked, 0);

  // 10. finishCurrentRun packs snapshot summary metrics and clears active state
  const sessionClient = createSnapshotClient();
  const sessionResult = await runSnapshotSession(
    sessionClient,
    path.join(tmpDir, 'session.test.js'),
    'helper test',
    { snapshotEnvironment: snapEnv, updateSnapshot: 'new' },
    (c) => {
      c.assert({ received: { message: 'hello session' } });
    }
  );

  assert.strictEqual(sessionResult.added, 1);
  assert.strictEqual(sessionClient.snapshotState, undefined);

  // clearTest clears filepath and name
  sessionClient.clearTest();
  assert.strictEqual(sessionClient.filepath, undefined);
  assert.strictEqual(sessionClient.name, undefined);

  // 11. clear resets all cached SnapshotState instances in the client map
  assert.ok(sessionClient.snapshotStateMap.size > 0);
  sessionClient.clear();
  assert.strictEqual(sessionClient.snapshotStateMap.size, 0);

  console.log('All SnapshotClient contract tests passed successfully.');
} finally {
  fs.rmSync(tmpDir, { recursive: true, force: true });
}

原始种子者

匿名