CodeSampleX

샘플

@vitest/snapshot 4.1.10: SnapshotState, NodeSnapshotEnvironment

검증된 샘플 — npm @vitest/snapshot 4.1.10: SnapshotState, NodeSnapshotEnvironment. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:7963788fb704aa209eb42509e72901e96a40970a125449919bf6ee8fcf3dee58

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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 });
}

오리진 시더

익명