CodeSampleX

샘플

@jest/schemas 29.6.3: validate Jest snapshot formatting configuration using the SnapshotFormat schema

검증된 샘플 — npm @jest/schemas 29.6.3: validate Jest snapshot formatting configuration using the SnapshotFormat schema. node 22 · linux alpine/x64 · docker에서…

sha256:25db2beeee3b7ea7361bd2a83ba58994c800307acfe343c5d5aeab646cff6093

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

케이스

HOW
목표
validate Jest snapshot formatting configuration using the SnapshotFormat schema
패키지
심벌
  • SnapshotFormat
환경
node 22.23.2
생성일
2026-08-21T05:11:14Z

컨트랙트

  1. SnapshotFormat provides the JSON schema definition for Jest snapshot options
  2. validateSnapshotFormat validates compliant snapshot formatting options including indent and theme
  3. validateSnapshotFormat accepts empty configuration as all SnapshotFormat options are optional
  4. validateSnapshotFormat rejects invalid option types and negative indentation values
  5. validateSnapshotFormat rejects unrecognized top-level and nested theme properties

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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: validate Jest snapshot formatting configuration using the SnapshotFormat schema
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40jest/schemas@29.6.3
Demonstrate these symbols/APIs:
  - SnapshotFormat
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:ebd38b1df67a449b1bf03051805b16f5973cf4cb12a5d9c36aa5bab587169ca3","constraints":{"executionContext":"node"},"contract":["SnapshotFormat provides the JSON schema definition for Jest snapshot options","validateSnapshotFormat validates compliant snapshot formatting options including indent and theme","validateSnapshotFormat accepts empty configuration as all SnapshotFormat options are optional","validateSnapshotFormat rejects invalid option types and negative indentation values","validateSnapshotFormat rejects unrecognized top-level and nested theme properties"],"goal":"validate Jest snapshot formatting configuration using the SnapshotFormat schema","kind":"HOW","packages":["pkg:npm/%40jest/schemas@29.6.3"],"schemaVersion":1,"symbols":["SnapshotFormat"]},"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/%40jest/schemas@29.6.3"],"schemaVersion":1,"subject":"pkg:npm/%40jest/schemas@29.6.3","symbols":["SnapshotFormat"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jest-schemas",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-schemas",
      "version": "1.0.0",
      "dependencies": {
        "@jest/schemas": "29.6.3"
      }
    },
    "node_modules/@jest/schemas": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
      "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
      "license": "MIT",
      "dependencies": {
        "@sinclair/typebox": "^0.27.8"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.27.12",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
      "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-jest-schemas",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @jest/schemas",
  "main": "src/index.js",
  "dependencies": {
    "@jest/schemas": "29.6.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "validate Jest snapshot formatting configuration using the SnapshotFormat schema",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40jest/schemas@29.6.3"
  ],
  "symbols": [
    "SnapshotFormat"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { SnapshotFormat } = require('@jest/schemas');

/**
 * Validates a snapshot format configuration object against the SnapshotFormat schema.
 *
 * @param {Record<string, unknown>} options - Configuration options to validate.
 * @returns {{ isValid: boolean, errors: string[] }} Result of validation.
 */
function validateSnapshotFormat(options) {
  if (typeof options !== 'object' || options === null || Array.isArray(options)) {
    return {
      isValid: false,
      errors: ['SnapshotFormat options must be a plain object']
    };
  }

  const errors = [];
  const schemaProps = SnapshotFormat.properties;

  for (const key of Object.keys(options)) {
    if (!Object.prototype.hasOwnProperty.call(schemaProps, key)) {
      errors.push(`Unknown option: "${key}"`);
      continue;
    }

    const val = options[key];
    if (val === undefined) {
      continue;
    }

    const propSchema = schemaProps[key];

    if (key === 'theme') {
      if (typeof val !== 'object' || val === null || Array.isArray(val)) {
        errors.push('Option "theme" must be an object');
      } else {
        const themeProps = propSchema.properties;
        for (const themeKey of Object.keys(val)) {
          if (!Object.prototype.hasOwnProperty.call(themeProps, themeKey)) {
            errors.push(`Unknown theme option: "${themeKey}"`);
          } else if (val[themeKey] !== undefined && typeof val[themeKey] !== 'string') {
            errors.push(`Option "theme.${themeKey}" must be a string`);
          }
        }
      }
    } else if (propSchema.type === 'boolean') {
      if (typeof val !== 'boolean') {
        errors.push(`Option "${key}" must be a boolean`);
      }
    } else if (propSchema.type === 'number') {
      if (typeof val !== 'number' || Number.isNaN(val) || (propSchema.minimum !== undefined && val < propSchema.minimum)) {
        errors.push(`Option "${key}" must be a number >= ${propSchema.minimum ?? 0}`);
      }
    } else if (propSchema.type === 'null') {
      if (val !== null) {
        errors.push(`Option "${key}" must be null`);
      }
    }
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

module.exports = {
  SnapshotFormat,
  validateSnapshotFormat
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { SnapshotFormat, validateSnapshotFormat } = require('../src/index.js');

// 1. Symbol & Schema verification
assert.strictEqual(typeof SnapshotFormat, 'object', 'SnapshotFormat should be an object');
assert.strictEqual(SnapshotFormat.type, 'object', 'SnapshotFormat schema type should be object');
assert.ok(SnapshotFormat.properties, 'SnapshotFormat schema should have properties');
assert.strictEqual(typeof SnapshotFormat.properties.indent, 'object', 'indent property schema should exist');
assert.strictEqual(SnapshotFormat.properties.indent.minimum, 0, 'indent minimum should be 0');
assert.strictEqual(SnapshotFormat.properties.theme.type, 'object', 'theme property should be an object');
assert.strictEqual(typeof validateSnapshotFormat, 'function', 'validateSnapshotFormat should be a function');

// 2. Validate valid snapshot format configuration
const validConfig = {
  callToJSON: true,
  escapeRegex: false,
  escapeString: true,
  highlight: false,
  indent: 2,
  maxDepth: 10,
  maxWidth: 80,
  min: false,
  printBasicPrototype: true,
  printFunctionName: true,
  theme: {
    comment: 'gray',
    content: 'reset',
    prop: 'yellow',
    tag: 'cyan',
    value: 'green'
  }
};

const validResult = validateSnapshotFormat(validConfig);
assert.deepStrictEqual(validResult, {
  isValid: true,
  errors: []
}, 'Valid configuration should pass validation without errors');

// 3. Validate empty / partial configuration (all properties are optional in SnapshotFormat)
const emptyResult = validateSnapshotFormat({});
assert.strictEqual(emptyResult.isValid, true, 'Empty configuration should be valid');

// 4. Reject invalid options, types, and out-of-bound values
const invalidTypesConfig = {
  callToJSON: 'not-a-boolean',
  indent: -2,
  compareKeys: 'not-null'
};
const invalidTypesResult = validateSnapshotFormat(invalidTypesConfig);
assert.strictEqual(invalidTypesResult.isValid, false, 'Invalid types should fail validation');
assert.ok(invalidTypesResult.errors.some(e => e.includes('callToJSON')), 'Should report error for callToJSON');
assert.ok(invalidTypesResult.errors.some(e => e.includes('indent')), 'Should report error for indent');
assert.ok(invalidTypesResult.errors.some(e => e.includes('compareKeys')), 'Should report error for compareKeys');

// 5. Reject unknown properties and invalid nested theme properties
const unknownPropsConfig = {
  unrecognizedProperty: true,
  theme: {
    invalidThemeField: 123,
    comment: 456
  }
};
const unknownPropsResult = validateSnapshotFormat(unknownPropsConfig);
assert.strictEqual(unknownPropsResult.isValid, false, 'Unknown properties should fail validation');
assert.ok(unknownPropsResult.errors.some(e => e.includes('unrecognizedProperty')), 'Should report error for unrecognized property');
assert.ok(unknownPropsResult.errors.some(e => e.includes('invalidThemeField')), 'Should report error for unrecognized theme field');
assert.ok(unknownPropsResult.errors.some(e => e.includes('theme.comment')), 'Should report error for non-string theme.comment');

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

오리진 시더

익명