CodeSampleX

Пример

chai 5.3.3: expect

Проверенный пример — npm chai 5.3.3: expect. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: expect(val).to.equal and expect(val).to.be.a…

sha256:a464fe0e59bc6e56e780fcea83fbc705b89a7483ec5a22bcb6b5410a390d887c

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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 expect in pkg:npm/chai@5.3.3
Пакеты
Символы
  • expect
Создан
2026-08-27T05:13:32Z

Контракт

  1. expect(val).to.equal and expect(val).to.be.a validate value equality and runtime type checking
  2. expect(obj).to.deep.equal validates structural equality across nested objects and arrays
  3. expect(num).to.be.at.least and expect(num).to.be.at.most validate inclusive numeric boundaries
  4. expect(col).to.include and expect(col).to.have.lengthOf verify collection containment and size
  5. expect(obj).to.have.property verifies property existence and chaining assertions on property values
  6. expect(fn).to.throw asserts exception thrown matching constructor or pattern and throws AssertionError on failure

Файлы

  • 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: verify expect in pkg:npm/chai@5.3.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/chai@5.3.3
Demonstrate these symbols/APIs:
  - expect

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:7acb82b2dc01c7559e4c86aa32ea00a5f61dc89b7123e49669974242912dfa62","contract":["expect(val).to.equal and expect(val).to.be.a validate value equality and runtime type checking","expect(obj).to.deep.equal validates structural equality across nested objects and arrays","expect(num).to.be.at.least and expect(num).to.be.at.most validate inclusive numeric boundaries","expect(col).to.include and expect(col).to.have.lengthOf verify collection containment and size","expect(obj).to.have.property verifies property existence and chaining assertions on property values","expect(fn).to.throw asserts exception thrown matching constructor or pattern and throws AssertionError on failure"],"goal":"verify expect in pkg:npm/chai@5.3.3","kind":"HOW","packages":["pkg:npm/chai@5.3.3"],"schemaVersion":1,"symbols":["expect"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/chai@5.3.3"],"schemaVersion":1,"subject":"pkg:npm/chai@5.3.3","symbols":["expect"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-chai-expect",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-chai-expect",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "chai": "5.3.3"
      }
    },
    "node_modules/assertion-error": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
      "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/chai": {
      "version": "5.3.3",
      "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
      "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
      "license": "MIT",
      "dependencies": {
        "assertion-error": "^2.0.1",
        "check-error": "^2.1.1",
        "deep-eql": "^5.0.1",
        "loupe": "^3.1.0",
        "pathval": "^2.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/check-error": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
      "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
      "license": "MIT",
      "engines": {
        "node": ">= 16"
      }
    },
    "node_modules/deep-eql": {
      "version": "5.0.2",
      "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
      "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/loupe": {
      "version": "3.2.1",
      "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
      "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
      "license": "MIT"
    },
    "node_modules/pathval": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
      "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 14.16"
      }
    }
  }
}
package.json
{
  "name": "sample-chai-expect",
  "version": "1.0.0",
  "description": "Clean-room verification of expect in chai",
  "type": "module",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "chai": "5.3.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify expect in pkg:npm/chai@5.3.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/chai@5.3.3"
  ],
  "symbols": [
    "expect"
  ]
}
src/index.js
import { expect } from "chai";

/**
 * Validates strict equality and basic type checking using expect.
 *
 * @param {unknown} actual - Actual value to test.
 * @param {unknown} expected - Expected value.
 * @param {string} [expectedType] - Optional type string.
 * @returns {boolean} True if assertions pass.
 */
export function verifyBasicExpectation(actual, expected, expectedType) {
  expect(actual).to.equal(expected);
  if (expectedType) {
    expect(actual).to.be.a(expectedType);
  }
  return true;
}

/**
 * Validates deep structural equality on objects and arrays.
 *
 * @param {unknown} actual - Actual data structure.
 * @param {unknown} expected - Expected data structure.
 * @returns {boolean} True if assertions pass.
 */
export function verifyDeepEquality(actual, expected) {
  expect(actual).to.deep.equal(expected);
  return true;
}

/**
 * Validates numeric range comparisons and boundary conditions.
 *
 * @param {number} value - Numeric value under test.
 * @param {number} min - Lower boundary (inclusive).
 * @param {number} max - Upper boundary (inclusive).
 * @returns {boolean} True if assertions pass.
 */
export function verifyNumericRange(value, min, max) {
  expect(value).to.be.at.least(min);
  expect(value).to.be.at.most(max);
  return true;
}

/**
 * Validates collection membership, string inclusion, and size.
 *
 * @param {Array|string|Set} collection - Target collection or string.
 * @param {unknown} item - Item expected to be included.
 * @param {number} length - Expected length or size.
 * @returns {boolean} True if assertions pass.
 */
export function verifyCollectionAndLength(collection, item, length) {
  expect(collection).to.have.lengthOf(length);
  expect(collection).to.include(item);
  return true;
}

/**
 * Validates nested property existence and values.
 *
 * @param {object} target - Target object.
 * @param {string} propertyPath - Property name to verify.
 * @param {unknown} expectedValue - Expected value for property.
 * @returns {boolean} True if assertions pass.
 */
export function verifyProperty(target, propertyPath, expectedValue) {
  expect(target).to.have.property(propertyPath).that.equals(expectedValue);
  return true;
}

/**
 * Validates function execution and exception throwing.
 *
 * @param {() => unknown} fn - Function to invoke.
 * @param {Function} [errorConstructor] - Expected Error class.
 * @param {string|RegExp} [matcher] - Expected error message substring or regex.
 * @returns {boolean} True if assertions pass.
 */
export function verifyThrows(fn, errorConstructor, matcher) {
  if (errorConstructor && matcher) {
    expect(fn).to.throw(errorConstructor, matcher);
  } else if (errorConstructor) {
    expect(fn).to.throw(errorConstructor);
  } else {
    expect(fn).to.throw();
  }
  return true;
}

export { expect };
test/contract.mjs
import { expect } from "chai";
import {
  verifyBasicExpectation,
  verifyDeepEquality,
  verifyNumericRange,
  verifyCollectionAndLength,
  verifyProperty,
  verifyThrows,
} from "../src/index.js";

async function runContract() {
  // 1. Value equality and type checking
  expect("hello world").to.be.a("string");
  expect(42).to.be.a("number");
  expect(true).to.be.a("boolean");
  expect([1, 2, 3]).to.be.an("array");
  expect({ key: "val" }).to.be.an("object");
  expect(new Date()).to.be.an.instanceOf(Date);
  expect("hello").to.equal("hello");
  expect("hello").to.not.equal("world");
  expect(verifyBasicExpectation(100, 100, "number")).to.be.true;

  // 2. Structural deep equality
  const objA = { user: { id: 1, roles: ["admin", "user"] }, active: true };
  const objB = { user: { id: 1, roles: ["admin", "user"] }, active: true };
  const objC = { user: { id: 1, roles: ["guest"] }, active: false };
  expect(objA).to.deep.equal(objB);
  expect(objA).to.not.deep.equal(objC);
  expect(verifyDeepEquality(objA, objB)).to.be.true;

  // 3. Numeric bounds and comparisons
  expect(10).to.be.at.least(5);
  expect(10).to.be.at.least(10);
  expect(10).to.be.at.most(15);
  expect(10).to.be.at.most(10);
  expect(10).to.be.above(9);
  expect(10).to.be.below(11);
  expect(verifyNumericRange(25, 10, 50)).to.be.true;

  // 4. Collection membership and length
  const fruits = ["apple", "banana", "cherry"];
  expect(fruits).to.have.lengthOf(3);
  expect(fruits).to.include("banana");
  expect(fruits).to.not.include("mango");
  expect("supercalifragilistic").to.include("cali");
  expect("supercalifragilistic").to.have.lengthOf(20);
  expect(verifyCollectionAndLength(fruits, "banana", 3)).to.be.true;

  // 5. Property assertions and chaining
  const config = { database: { host: "localhost", port: 5432 }, retries: 3 };
  expect(config).to.have.property("retries").that.equals(3);
  expect(config).to.have.nested.property("database.port", 5432);
  expect(verifyProperty(config, "retries", 3)).to.be.true;

  // 6. Exceptions and AssertionError behavior
  const failingFn = () => {
    throw new TypeError("Invalid argument provided");
  };
  expect(failingFn).to.throw(TypeError, /Invalid argument/);
  expect(verifyThrows(failingFn, TypeError, "Invalid argument provided")).to.be.true;

  const safeFn = () => "ok";
  expect(safeFn).to.not.throw();

  let threwAssertionError = false;
  try {
    expect(1).to.equal(2);
  } catch (err) {
    threwAssertionError = true;
    expect(err.name).to.equal("AssertionError");
  }
  expect(threwAssertionError).to.be.true;

  console.log("Chai expect contract tests passed successfully.");
}

runContract().catch((err) => {
  console.error("Contract test failed:", err);
  process.exit(1);
});

Исходный сидер

аноним