CodeSampleX

Beispiel

@vitest/snapshot 3.2.7: Manage test snapshot states and match assertions using SnapshotState and NodeSnapshotEnvironment

Verifiziertes Beispiel für npm @vitest/snapshot 3.2.7: Manage test snapshot states and match assertions using SnapshotState and NodeSnapshotEnvironment. Der…

sha256:961d44ea6c77e7db44c9f2df6edecde79434e806ec9888b8a786df5324b6145e

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung node linux 24 · ubuntu · glibc 2.39 x64 node node npm

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Manage test snapshot states and match assertions using SnapshotState and NodeSnapshotEnvironment
Pakete
Symbole
  • SnapshotState
  • NodeSnapshotEnvironment
Umgebung
node
Erstellt
2026-08-23T14:49:45Z

Contract

  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 with actual/expected diffs on mismatch.
  4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions.

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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

Search via `search_known_solution` returned `NO_SAFE_MATCH`, 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 with actual/expected diffs on mismatch.
- `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: Manage test snapshot states and match assertions using SnapshotState and NodeSnapshotEnvironment
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/snapshot@3.2.7

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:03667502edc145b4ce17e23bfcfc67b2c1b11d33b1ef3164eafb5393f247835b","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 with actual/expected diffs on mismatch.","SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions."],"goal":"Manage test snapshot states and match assertions using SnapshotState and NodeSnapshotEnvironment","kind":"HOW","packages":["pkg:npm/%40vitest/snapshot@3.2.7"],"schemaVersion":1,"symbols":["SnapshotState","NodeSnapshotEnvironment"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"node","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/snapshot@3.2.7"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/snapshot@3.2.7","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": "npm-vitest-snapshot-snapshotstate-nodesnapshotenvironment",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-vitest-snapshot-snapshotstate-nodesnapshotenvironment",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/snapshot": "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/@vitest/pretty-format": {
      "version": "3.2.7",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz",
      "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^2.0.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/snapshot": {
      "version": "3.2.7",
      "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz",
      "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "3.2.7",
        "magic-string": "^0.30.17",
        "pathe": "^2.0.3"
      },
      "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": "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": "2.0.0",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",
      "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "npm-vitest-snapshot-snapshotstate-nodesnapshotenvironment",
  "version": "1.0.0",
  "type": "module",
  "description": "Code sample for @vitest/snapshot SnapshotState and NodeSnapshotEnvironment",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/snapshot": "3.2.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Manage test snapshot states and match assertions using SnapshotState and NodeSnapshotEnvironment",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/snapshot@3.2.7"
  ]
}
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 creates 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', match returns pass: true for matching received data
  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', match returns pass: false and formatted actual/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 summary counts of matched and unmatched snapshots
  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 });
}

Ursprungs-Seeder

anonym