Пример
jest-each 29.7.0: parameterized tests using jest-each table and template literal
Проверенный пример — npm jest-each 29.7.0: parameterized tests using jest-each table and template literal. Контракт выполнен на node 22 · linux alpine/x64 …
sha256:b4a84c97f6d4438d3ddf0f03ab74419b0e472ec799a8abd3c677758eb2834512
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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- Цель
- parameterized tests using jest-each table and template literal
- Пакеты
- Символы
-
- each
- Создан
- 2026-08-27T16:30:46Z
Контракт
- each with 2D array table formats test titles using %i, %s, %d placeholders and passes row elements as arguments
- each tagged template literal parses column headings and passes interpolated values as named object parameters
- each.withGlobal binds parameterized tests to custom test runner globals
- each describe formats suite titles and executes describe suite callback for each row
- bind directly wraps a custom test runner callback with 1D and 2D arrays
- bind passes error to test runner callback when called with non-array table
- bind passes error to test runner callback when called with empty array
- each.withGlobal throws error when called with invalid table data arguments
Файлы
- PROMPT.md
- README.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- test/contract.mjs
Исходный код
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: parameterized tests using jest-each table and template literal
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jest-each@29.7.0
Demonstrate these symbols/APIs:
- each
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.
# jest-each Parameterized Testing Sample
This sample demonstrates how to write parameterized tests using `jest-each` with:
- 2D and 1D array tables and placeholder formatting (`%s`, `%i`, `%d`)
- Tagged template literal tables with column headings and `$variable` interpolation
- Custom test runner binding via `each.withGlobal` and `bind`
{"case":{"caseId":"case:sha256:78b63439897d40c3ccab961f3272a9719e7337ca0767f3a2b31817917cb63209","contract":["each with 2D array table formats test titles using %i, %s, %d placeholders and passes row elements as arguments","each tagged template literal parses column headings and passes interpolated values as named object parameters","each.withGlobal binds parameterized tests to custom test runner globals","each describe formats suite titles and executes describe suite callback for each row","bind directly wraps a custom test runner callback with 1D and 2D arrays","bind passes error to test runner callback when called with non-array table","bind passes error to test runner callback when called with empty array","each.withGlobal throws error when called with invalid table data arguments"],"goal":"parameterized tests using jest-each table and template literal","kind":"HOW","packages":["pkg:npm/jest-each@29.7.0"],"schemaVersion":1,"symbols":["each"]},"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/jest-each@29.7.0"],"schemaVersion":1,"subject":"pkg:npm/jest-each@29.7.0","symbols":["each"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-jest-each",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-jest-each",
"version": "1.0.0",
"dependencies": {
"jest-each": "29.7.0"
}
},
"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/@jest/types": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz",
"integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==",
"license": "MIT",
"dependencies": {
"@jest/schemas": "^29.6.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
"@types/yargs": "^17.0.8",
"chalk": "^4.0.0"
},
"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"
},
"node_modules/@types/istanbul-lib-coverage": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
"integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
"license": "MIT"
},
"node_modules/@types/istanbul-lib-report": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz",
"integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==",
"license": "MIT",
"dependencies": {
"@types/istanbul-lib-coverage": "*"
}
},
"node_modules/@types/istanbul-reports": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz",
"integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==",
"license": "MIT",
"dependencies": {
"@types/istanbul-lib-report": "*"
}
},
"node_modules/@types/node": {
"version": "26.4.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
"integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/@types/yargs": {
"version": "17.0.35",
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
"integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==",
"license": "MIT",
"dependencies": {
"@types/yargs-parser": "*"
}
},
"node_modules/@types/yargs-parser": {
"version": "21.0.3",
"resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
"license": "MIT"
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"license": "MIT",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/ci-info": {
"version": "3.9.0",
"resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
"integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/sibiraj-s"
}
],
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"license": "MIT",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/jest-each": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz",
"integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==",
"license": "MIT",
"dependencies": {
"@jest/types": "^29.6.3",
"chalk": "^4.0.0",
"jest-get-type": "^29.6.3",
"jest-util": "^29.7.0",
"pretty-format": "^29.7.0"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/jest-get-type": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz",
"integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==",
"license": "MIT",
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/jest-util": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz",
"integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==",
"license": "MIT",
"dependencies": {
"@jest/types": "^29.6.3",
"@types/node": "*",
"chalk": "^4.0.0",
"ci-info": "^3.2.0",
"graceful-fs": "^4.2.9",
"picomatch": "^2.2.3"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/picomatch": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
"license": "MIT",
"engines": {
"node": ">=8.6"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/pretty-format": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz",
"integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==",
"license": "MIT",
"dependencies": {
"@jest/schemas": "^29.6.3",
"ansi-styles": "^5.0.0",
"react-is": "^18.0.0"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/pretty-format/node_modules/ansi-styles": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
"license": "MIT"
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"license": "MIT"
}
}
}
{
"name": "sample-jest-each",
"version": "1.0.0",
"private": true,
"type": "module",
"dependencies": {
"jest-each": "29.7.0"
}
}
{
"schemaVersion": 1,
"goal": "parameterized tests using jest-each table and template literal",
"kind": "HOW",
"packages": [
"pkg:npm/jest-each@29.7.0"
],
"symbols": [
"each"
]
}
import eachPkg, { bind } from 'jest-each';
const each = eachPkg.default || eachPkg;
/**
* Runs parameterized tests against an array of test cases.
*
* @param {Array<Array<any>>} table - Table of test case input parameters.
* @param {string} title - Test title template with placeholders (%s, %i, %d, %j, %o).
* @param {Function} testFn - Test callback function.
* @param {Object} [customGlobal] - Optional global test environment mock.
*/
export function runArrayTests(table, title, testFn, customGlobal) {
const runner = customGlobal ? each.withGlobal(customGlobal) : each;
return runner(table).test(title, testFn);
}
/**
* Runs parameterized tests with tagged template literal table syntax.
*
* @param {TemplateStringsArray} strings - Template literal strings defining header and row delimiters.
* @param {...any} expressions - Interpolated test values.
* @returns {{ test: Function, describe: Function }}
*/
export function templateEach(strings, ...expressions) {
return each(strings, ...expressions);
}
/**
* Directly binds a custom test runner callback for parameterized execution.
*
* @param {Function} runner - Custom test runner (title, testFn) => void.
* @param {Array<any>} table - Test cases table.
* @param {string} title - Title template.
* @param {Function} testFn - Test function.
*/
export function runWithCustomRunner(runner, table, title, testFn) {
const boundTest = bind(runner)(table);
return boundTest(title, testFn);
}
export { each, bind };
import assert from 'node:assert/strict';
import eachPkg, { bind } from 'jest-each';
import { runArrayTests, runWithCustomRunner } from '../src/index.mjs';
const each = eachPkg.default || eachPkg;
function createMockGlobal() {
const recorded = [];
const makeTestFn = (name) => {
const fn = (title, testFn) => {
recorded.push({ type: name, title, testFn });
};
fn.skip = (title, testFn) => recorded.push({ type: `${name}.skip`, title, testFn });
fn.only = (title, testFn) => recorded.push({ type: `${name}.only`, title, testFn });
const concurrent = (title, testFn) => recorded.push({ type: `${name}.concurrent`, title, testFn });
concurrent.only = (title, testFn) => recorded.push({ type: `${name}.concurrent.only`, title, testFn });
concurrent.skip = (title, testFn) => recorded.push({ type: `${name}.concurrent.skip`, title, testFn });
fn.concurrent = concurrent;
return fn;
};
const makeDescribeFn = (name) => {
const fn = (title, suiteFn) => {
recorded.push({ type: name, title, suiteFn });
};
fn.skip = (title, suiteFn) => recorded.push({ type: `${name}.skip`, title, suiteFn });
fn.only = (title, suiteFn) => recorded.push({ type: `${name}.only`, title, suiteFn });
return fn;
};
const g = {
test: makeTestFn('test'),
it: makeTestFn('it'),
xit: (title, testFn) => recorded.push({ type: 'xit', title, testFn }),
fit: (title, testFn) => recorded.push({ type: 'fit', title, testFn }),
xtest: (title, testFn) => recorded.push({ type: 'xtest', title, testFn }),
describe: makeDescribeFn('describe'),
fdescribe: (title, suiteFn) => recorded.push({ type: 'fdescribe', title, suiteFn }),
xdescribe: (title, suiteFn) => recorded.push({ type: 'xdescribe', title, suiteFn })
};
return { g, recorded };
}
// 1. Array table syntax with %i, %s and %d formatting via withGlobal
{
const { g, recorded } = createMockGlobal();
const customEach = each.withGlobal(g);
customEach([
[1, 2, 3],
[2, 3, 5],
[10, -5, 5]
]).test('adds %i + %i = %i', (a, b, expected) => {
assert.equal(a + b, expected);
});
assert.equal(recorded.length, 3);
assert.equal(recorded[0].title, 'adds 1 + 2 = 3');
assert.equal(recorded[1].title, 'adds 2 + 3 = 5');
assert.equal(recorded[2].title, 'adds 10 + -5 = 5');
for (const item of recorded) {
item.testFn();
}
}
// 2. Tagged template literal syntax with object destructuring and $variable formatting
{
const { g, recorded } = createMockGlobal();
const customEach = each.withGlobal(g);
customEach`
a | b | expected
${2} | ${3} | ${6}
${4} | ${5} | ${20}
`.test('multiplies $a * $b to get $expected', ({ a, b, expected }) => {
assert.equal(a * b, expected);
});
assert.equal(recorded.length, 2);
assert.equal(recorded[0].title, 'multiplies 2 * 3 to get 6');
assert.equal(recorded[1].title, 'multiplies 4 * 5 to get 20');
for (const item of recorded) {
item.testFn();
}
}
// 3. Direct bind API with 2D array and custom runner
{
const recorded = [];
const runner = (title, testFn) => {
recorded.push({ title, testFn });
};
const eachTest = bind(runner)([
['hello', 5],
['world', 5],
['antigravity', 11]
]);
eachTest('length of "%s" is %i', (str, len) => {
assert.equal(str.length, len);
});
assert.equal(recorded.length, 3);
assert.equal(recorded[0].title, 'length of "hello" is 5');
assert.equal(recorded[1].title, 'length of "world" is 5');
assert.equal(recorded[2].title, 'length of "antigravity" is 11');
for (const item of recorded) {
item.testFn();
}
}
// 4. describe suite parameterization with withGlobal
{
const { g, recorded } = createMockGlobal();
const customEach = each.withGlobal(g);
customEach([
['admin', true],
['guest', false]
]).describe('User role %s (isAdmin: %s)', (role, isAdmin) => {
assert.equal(typeof role, 'string');
assert.equal(typeof isAdmin, 'boolean');
});
assert.equal(recorded.length, 2);
assert.equal(recorded[0].title, 'User role admin (isAdmin: true)');
assert.equal(recorded[1].title, 'User role guest (isAdmin: false)');
for (const item of recorded) {
item.suiteFn();
}
}
// 5. 1D Array syntax passes element directly as parameter
{
const recorded = [];
const runner = (title, testFn) => {
recorded.push({ title, testFn });
};
const eachTest = bind(runner)(['alpha', 'beta', 'gamma']);
eachTest('item: %s', (item) => {
assert.equal(typeof item, 'string');
});
assert.equal(recorded.length, 3);
assert.equal(recorded[0].title, 'item: alpha');
assert.equal(recorded[1].title, 'item: beta');
assert.equal(recorded[2].title, 'item: gamma');
for (const item of recorded) {
item.testFn();
}
}
// 6. Validation: bind throws when called with non-array table
{
const errors = [];
const runner = (title, testFn) => {
try {
testFn();
} catch (err) {
errors.push(err);
}
};
bind(runner)(12345)('invalid table type', () => {});
assert.equal(errors.length, 1);
assert.match(errors[0].message, /must be called with an Array or Tagged Template Literal/);
}
// 7. Validation: bind throws when called with empty array
{
const errors = [];
const runner = (title, testFn) => {
try {
testFn();
} catch (err) {
errors.push(err);
}
};
bind(runner)([])('empty array', () => {});
assert.equal(errors.length, 1);
assert.match(errors[0].message, /called with an empty Array of table data/);
}
// 8. Validation: install throws when called with invalid data arguments
{
const { g } = createMockGlobal();
assert.throws(
() => {
each.withGlobal(g)(12345, 'extra-arg');
},
/must only be called with an Array or Tagged Template Literal/
);
}
// 9. Helper wrapper functions verification
{
const { g, recorded } = createMockGlobal();
runArrayTests([[10, 20]], 'test %i %i', (a, b) => {
assert.equal(a + b, 30);
}, g);
assert.equal(recorded.length, 1);
assert.equal(recorded[0].title, 'test 10 20');
recorded[0].testFn();
const runnerItems = [];
runWithCustomRunner((title, testFn) => {
runnerItems.push({ title, testFn });
}, [[1, 2]], 'sum %i %i', (x, y) => {
assert.equal(x + y, 3);
});
assert.equal(runnerItems.length, 1);
assert.equal(runnerItems[0].title, 'sum 1 2');
runnerItems[0].testFn();
}
console.log('Contract tests passed successfully.');
Исходный сидер
аноним