CodeSampleX

Пример

@vitest/expect 2.1.9: addCustomEqualityTesters

Проверенный пример — npm @vitest/expect 2.1.9: addCustomEqualityTesters. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:01996734758e9a91379a1dda50dc3e9bdb6f52f42f24c96825ca177b8f5e529b

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

Кейс

HOW
Цель
verify @vitest/expect.addCustomEqualityTesters in pkg:npm/%40vitest/expect@2.1.9
Пакеты
Символы
  • @vitest/expect.addCustomEqualityTesters
Окружение
node 22.23.2
Создан
2026-09-06T16:03:51Z

Контракт

  1. addCustomEqualityTesters throws TypeError when argument is not an array
  2. addCustomEqualityTesters registers custom equality tester enabling deep equality comparison for custom types
  3. addCustomEqualityTesters enables custom equality tester to return undefined to fall back to default comparison
  4. addCustomEqualityTesters supports nested equality checks via TesterContext this.equals

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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 @vitest/expect.addCustomEqualityTesters in pkg:npm/%40vitest/expect@2.1.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/expect@2.1.9
Demonstrate these symbols/APIs:
  - @vitest/expect.addCustomEqualityTesters

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:8145bd41ee9dc75700ca0304646ee43b460bc957e4400fb8f2c6338e5bfc741c","contract":["addCustomEqualityTesters throws TypeError when argument is not an array","addCustomEqualityTesters registers custom equality tester enabling deep equality comparison for custom types","addCustomEqualityTesters enables custom equality tester to return undefined to fall back to default comparison","addCustomEqualityTesters supports nested equality checks via TesterContext this.equals"],"goal":"verify @vitest/expect.addCustomEqualityTesters in pkg:npm/%40vitest/expect@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/expect@2.1.9"],"schemaVersion":1,"symbols":["@vitest/expect.addCustomEqualityTesters"]},"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/expect@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/expect@2.1.9","symbols":["@vitest/expect.addCustomEqualityTesters"],"verifierAdapter":"node-typescript@1"}
index.js
import * as chai from "chai";
import {
  addCustomEqualityTesters,
  equals,
  JestChaiExpect,
  JestExtend,
  JestAsymmetricMatchers,
} from "@vitest/expect";

/**
 * Initializes and returns a Chai expect instance equipped with Vitest matchers.
 * @returns {Function}
 */
export function createExpect() {
  chai.use(JestChaiExpect);
  chai.use(JestExtend);
  chai.use(JestAsymmetricMatchers);
  return chai.expect;
}

/**
 * Registers custom equality testers globally in Vitest expect matchers.
 * @param {Array<Function>} testers - Array of tester functions.
 */
export function registerCustomEqualityTesters(testers) {
  addCustomEqualityTesters(testers);
}

/**
 * Represents a case-insensitive string wrapper.
 */
export class CaseInsensitiveString {
  /**
   * @param {string} value
   */
  constructor(value) {
    this.value = value;
  }
}

/**
 * Custom equality tester for CaseInsensitiveString instances.
 * @param {unknown} a
 * @param {unknown} b
 * @returns {boolean|undefined}
 */
export function caseInsensitiveTester(a, b) {
  if (a instanceof CaseInsensitiveString && b instanceof CaseInsensitiveString) {
    return (
      typeof a.value === "string" &&
      typeof b.value === "string" &&
      a.value.toLowerCase() === b.value.toLowerCase()
    );
  }
  return undefined;
}

/**
 * Represents a composite container holding an inner value.
 */
export class ValueContainer {
  /**
   * @param {unknown} inner
   */
  constructor(inner) {
    this.inner = inner;
  }
}

/**
 * Custom equality tester for ValueContainer instances delegating inner comparison via this.equals.
 * @this {{ equals: Function }}
 * @param {unknown} a
 * @param {unknown} b
 * @param {Array<Function>} customTesters
 * @returns {boolean|undefined}
 */
export function valueContainerTester(a, b, customTesters) {
  if (a instanceof ValueContainer && b instanceof ValueContainer) {
    return this.equals(a.inner, b.inner, customTesters);
  }
  return undefined;
}

export { addCustomEqualityTesters, equals };
package-lock.json
{
  "name": "verify-vitest-expect-addcustomequalitytesters",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-vitest-expect-addcustomequalitytesters",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/expect": "2.1.9"
      }
    },
    "node_modules/@vitest/expect": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
      "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
      "license": "MIT",
      "dependencies": {
        "@vitest/spy": "2.1.9",
        "@vitest/utils": "2.1.9",
        "chai": "^5.1.2",
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/pretty-format": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
      "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/spy": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
      "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
      "license": "MIT",
      "dependencies": {
        "tinyspy": "^3.0.2"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/utils": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
      "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "2.1.9",
        "loupe": "^3.1.2",
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "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"
      }
    },
    "node_modules/tinyrainbow": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
      "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    },
    "node_modules/tinyspy": {
      "version": "3.0.2",
      "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
      "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "verify-vitest-expect-addcustomequalitytesters",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "description": "Clean-room verification sample for @vitest/expect addCustomEqualityTesters",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/expect": "2.1.9"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/expect.addCustomEqualityTesters in pkg:npm/%40vitest/expect@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/expect@2.1.9"
  ],
  "symbols": [
    "@vitest/expect.addCustomEqualityTesters"
  ]
}
test/contract.mjs
import assert from "node:assert/strict";
import {
  createExpect,
  addCustomEqualityTesters,
  registerCustomEqualityTesters,
  CaseInsensitiveString,
  caseInsensitiveTester,
  ValueContainer,
  valueContainerTester,
} from "../index.js";

const expect = createExpect();

async function runContractTests() {
  // Contract: addCustomEqualityTesters throws TypeError when argument is not an array
  {
    assert.throws(
      () => addCustomEqualityTesters(null),
      (err) => {
        return (
          err instanceof TypeError &&
          err.message.includes("expect.customEqualityTesters: Must be set to an array of Testers")
        );
      },
      "Must throw TypeError when passed null"
    );

    assert.throws(
      () => addCustomEqualityTesters("invalid"),
      (err) => {
        return (
          err instanceof TypeError &&
          err.message.includes("expect.customEqualityTesters: Must be set to an array of Testers")
        );
      },
      "Must throw TypeError when passed a string"
    );

    assert.throws(
      () => addCustomEqualityTesters({}),
      (err) => {
        return (
          err instanceof TypeError &&
          err.message.includes("expect.customEqualityTesters: Must be set to an array of Testers")
        );
      },
      "Must throw TypeError when passed an object"
    );

    // Empty array must be accepted without throwing
    addCustomEqualityTesters([]);
  }

  // Contract: addCustomEqualityTesters registers custom equality tester enabling deep equality comparison for custom types
  {
    registerCustomEqualityTesters([caseInsensitiveTester]);

    const strA = new CaseInsensitiveString("Hello World");
    const strB = new CaseInsensitiveString("HELLO WORLD");
    const strC = new CaseInsensitiveString("Different String");

    expect(strA).toEqual(strB);
    expect(strA).toStrictEqual(strB);
    expect(strA).not.toEqual(strC);

    // Also works when nested inside plain objects
    expect({ text: strA }).toEqual({ text: strB });
  }

  // Contract: addCustomEqualityTesters enables custom equality tester to return undefined to fall back to default comparison
  {
    // Tester returns undefined for values that are not CaseInsensitiveString,
    // so standard primitive and structural comparisons work as normal.
    expect({ id: 1, items: [10, 20] }).toEqual({ id: 1, items: [10, 20] });
    expect("direct string match").toEqual("direct string match");
    expect(true).toEqual(true);

    assert.throws(() => {
      expect({ id: 1 }).toEqual({ id: 2 });
    });
  }

  // Contract: addCustomEqualityTesters supports nested equality checks via TesterContext this.equals
  {
    registerCustomEqualityTesters([valueContainerTester]);

    const container1 = new ValueContainer({ code: 200, label: "OK" });
    const container2 = new ValueContainer({ code: 200, label: "OK" });
    const container3 = new ValueContainer({ code: 500, label: "ERROR" });

    expect(container1).toEqual(container2);
    expect(container1).not.toEqual(container3);

    // Nested custom testers work together: ValueContainer holding CaseInsensitiveString
    const mixed1 = new ValueContainer(new CaseInsensitiveString("Testing"));
    const mixed2 = new ValueContainer(new CaseInsensitiveString("TESTING"));
    expect(mixed1).toEqual(mixed2);

    // Array containing containers
    expect([container1]).toEqual([container2]);
  }

  console.log("All @vitest/expect.addCustomEqualityTesters contract tests passed successfully.");
}

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

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

аноним