CodeSampleX

示例

@vitest/snapshot 4.1.10: SnapshotState, NodeSnapshotEnvironment

已验证示例 — npm @vitest/snapshot 4.1.10: SnapshotState, NodeSnapshotEnvironment. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:7963788fb704aa209eb42509e72901e96a40970a125449919bf6ee8fcf3dee58

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

案例

HOW
目标
verify pkg:npm/%40vitest/snapshot@4.1.10
包
符号
  • SnapshotState
  • NodeSnapshotEnvironment
环境
node 22.23.2
创建时间
2026-08-27T22:49:32Z

契约

  1. SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'.
  2. SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents.
  3. When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch.
  4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions.

文件

  • NOTES.md
  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Notes on @vitest/snapshot SnapshotState and NodeSnapshotEnvironment

Search via `search_known_solution` returned `REFERENCE_ONLY` for previous versions (2.1.9, 3.2.7) and MISS for 4.1.10, requiring fresh verification.

## API Characteristics

1. **Snapshot State Initialization:**
   `SnapshotState.create(testFilePath, options)` initializes a snapshot management instance. It requires `snapshotEnvironment` (an instance of `NodeSnapshotEnvironment` or custom `SnapshotEnvironment`) and `updateSnapshot` mode (`'all'`, `'new'`, or `'none'`).

2. **Matching and Formatting:**
   - Calling `state.match(...)` compares the serialized representation of `received` data against stored snapshots.
   - When updating or matching successfully, `pass` is `true`.
   - When `updateSnapshot: 'none'` and values differ, `pass` is `false`, and formatted strings are provided in `actual` and `expected`.
   - `state.save()` commits the snapshot file to disk via the configured `SnapshotEnvironment`.

3. **Metrics Reporting:**
   - Calling `state.pack()` produces a `SnapshotResult` containing counts of `added`, `matched`, `unmatched`, `updated`, and `unchecked` keys.

## Verified Contract

The contract in `test/contract.mjs` verifies:
- `SnapshotState.create` initializes state with `NodeSnapshotEnvironment` and matches new snapshots when `updateSnapshot` is `'all'`.
- `SnapshotState.prototype.save` writes snapshot files to disk with formatted serialized contents.
- When `updateSnapshot` is `'none'`, `SnapshotState.prototype.match` passes for matching values and fails on mismatch with actual/expected.
- `SnapshotState.prototype.pack` returns matched and unmatched counters for executed snapshot assertions.
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 pkg:npm/%40vitest/snapshot@4.1.10
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/snapshot@4.1.10
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:a5e2b5f05fd679025b485c9f9ef3ee4f46c384de0e0641965cc396726c665be3","constraints":{"executionContext":"node"},"contract":["SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'.","SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents.","When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch.","SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions."],"goal":"verify pkg:npm/%40vitest/snapshot@4.1.10","kind":"HOW","packages":["pkg:npm/%40vitest/snapshot@4.1.10"],"schemaVersion":1,"symbols":["SnapshotState","NodeSnapshotEnvironment"]},"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/snapshot@4.1.10"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/snapshot@4.1.10","symbols":["SnapshotState","NodeSnapshotEnvironment"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { SnapshotState } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';

export async function runSnapshotAssertion(testFilePath, testName, data) {
  const env = new NodeSnapshotEnvironment();
  const state = await SnapshotState.create(testFilePath, {
    updateSnapshot: 'all',
    snapshotEnvironment: env,
  });

  const result = state.match({
    testId: testName,
    testName,
    received: data,
    isInline: false,
  });

  if (result.pass) {
    await state.save();
  }

  return {
    pass: result.pass,
    key: result.key,
    pack: await state.pack(),
  };
}
package-lock.json
{
  "name": "sample-vitest-snapshot",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-snapshot",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/snapshot": "4.1.10"
      }
    },
    "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": "4.1.10",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
      "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^3.1.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/snapshot": {
      "version": "4.1.10",
      "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",
      "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "4.1.10",
        "@vitest/utils": "4.1.10",
        "magic-string": "^0.30.21",
        "pathe": "^2.0.3"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/utils": {
      "version": "4.1.10",
      "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
      "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "4.1.10",
        "convert-source-map": "^2.0.0",
        "tinyrainbow": "^3.1.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/convert-source-map": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
      "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
      "license": "MIT"
    },
    "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": "2.0.3",
      "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
      "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
      "license": "MIT"
    },
    "node_modules/tinyrainbow": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
      "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-snapshot",
  "version": "1.0.0",
  "type": "module",
  "description": "Code sample for @vitest/snapshot",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/snapshot": "4.1.10"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40vitest/snapshot@4.1.10",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/snapshot@4.1.10"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import { SnapshotState } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';

const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'vitest-snap-contract-'));
const testFile = path.join(tmpDir, 'example.test.js');
await fs.writeFile(testFile, '// snapshot target\n');

try {
  const env = new NodeSnapshotEnvironment();

  // 1. SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'
  const writeState = await SnapshotState.create(testFile, {
    updateSnapshot: 'all',
    snapshotEnvironment: env,
  });

  const writeResult = writeState.match({
    testId: 'test-1',
    testName: 'object snapshot test',
    received: { name: 'sample', count: 42 },
    isInline: false,
  });

  assert.equal(writeResult.pass, true, 'match returns pass: true when creating new snapshot');
  assert.equal(writeResult.key, 'object snapshot test 1', 'match assigns expected snapshot key');

  const saveStatus = await writeState.save();
  assert.equal(saveStatus.saved, true, 'save writes snapshot file to disk');

  const snapPath = await env.resolvePath(testFile);
  const snapContent = await fs.readFile(snapPath, 'utf8');
  assert.match(snapContent, /"count": 42/, 'saved snapshot contains serialized object properties');

  // 2. When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values
  const readState = await SnapshotState.create(testFile, {
    updateSnapshot: 'none',
    snapshotEnvironment: env,
  });

  const readMatch = readState.match({
    testId: 'test-1',
    testName: 'object snapshot test',
    received: { name: 'sample', count: 42 },
    isInline: false,
  });
  assert.equal(readMatch.pass, true, 'match returns pass: true against existing snapshot');

  // 3. When updateSnapshot is 'none', SnapshotState.prototype.match fails with actual and expected on mismatch
  const mismatchState = await SnapshotState.create(testFile, {
    updateSnapshot: 'none',
    snapshotEnvironment: env,
  });

  const mismatchResult = mismatchState.match({
    testId: 'test-1',
    testName: 'object snapshot test',
    received: { name: 'sample', count: 99 },
    isInline: false,
  });

  assert.equal(mismatchResult.pass, false, 'match returns pass: false on mismatch');
  assert.match(mismatchResult.actual, /"count": 99/, 'actual contains received formatted value');
  assert.match(mismatchResult.expected, /"count": 42/, 'expected contains stored formatted value');

  // 4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions
  const packResult = await mismatchState.pack();
  assert.equal(packResult.matched, 0, 'pack reflects 0 matches');
  assert.equal(packResult.unmatched, 1, 'pack reflects 1 unmatched snapshot');
} finally {
  await fs.rm(tmpDir, { recursive: true, force: true });
}

原始种子者

匿名