Write model-based tests with @xstate/test 2.0 beta, replace end-to-end tests with model-based tests without losing coverage, and visualize the model in Stately. Use for model-based testing, @xstate/test, generating tests from a state machine, testing every path, replacing Playwright, Cypress, Vitest, or Jest end-to-end tests with a model, coverage parity, or migrating from @xstate/test 0.x or 1.0 beta.
100%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Medium
Suggest reviewing before use
#!/usr/bin/env node
// Checks that every legacy end-to-end test has a parity ledger entry, and that
// each mapped assertion has execution evidence in every original project.
//
// Usage:
// node parity-check.mjs --inventory <baseline>... --ledger <file> --evidence <file>...
// [--current-inventory <file>...] [--root <dir>]
// node parity-check.mjs --inventory <file>... --init [--root <dir>] > e2e-parity.json
//
// Repeat --inventory once per runner (Playwright and Vitest, for example).
// --init prints a ledger skeleton with one "todo" entry per legacy test.
//
// Inventory formats (detected automatically):
// - Playwright: `npx playwright test --list --reporter=json > inventory.json`
// - Vitest: `npx vitest list <dir> --json=inventory.json` or a JSON run report
// - Generic: a JSON array of { "id": "..." } or { "file": "...", "name": "..." }
//
// Exit codes: 0 = parity complete, 1 = gaps found, 2 = bad input.
import { readFileSync } from 'node:fs';
import { relative, resolve, isAbsolute } from 'node:path';
import { isDeepStrictEqual } from 'node:util';
function arg(name) {
const i = process.argv.indexOf(`--${name}`);
return i === -1 ? undefined : process.argv[i + 1];
}
function args(name) {
return process.argv.flatMap((a, i) => (a === `--${name}` && process.argv[i + 1] ? [process.argv[i + 1]] : []));
}
function fail(message) {
console.error(`parity-check: ${message}`);
process.exit(2);
}
const inventoryPaths = args('inventory');
const ledgerPath = arg('ledger');
const root = resolve(arg('root') ?? process.cwd());
const init = process.argv.includes('--init');
if (inventoryPaths.length === 0 || (!ledgerPath && !init)) {
fail('usage: parity-check.mjs --inventory <baseline>... (--ledger <file> --evidence <file>... | --init) [--current-inventory <file>...]');
}
function readJson(path) {
try {
return JSON.parse(readFileSync(path, 'utf8'));
} catch (error) {
fail(`cannot read ${path}: ${error.message}`);
}
}
const normalizeFile = (file) =>
(isAbsolute(file) ? relative(root, file) : file).split('\\').join('/');
const testId = (file, titles) =>
`${normalizeFile(file)} > ${titles.filter(Boolean).join(' > ')}`;
// Returns one { id, project } record per test the runner reported.
function inventoryRecords(data) {
// Playwright JSON report: { suites: [{ file, specs, suites }], errors: [] }
if (data && Array.isArray(data.suites)) {
if (Array.isArray(data.errors) && data.errors.length > 0) {
const first = data.errors[0]?.message ?? JSON.stringify(data.errors[0]);
fail(`inventory has ${data.errors.length} collection error(s); fix them and list again. First: ${first}`);
}
const records = [];
const walk = (suite, titles, isFileSuite) => {
const path = isFileSuite ? titles : [...titles, suite.title];
for (const spec of suite.specs ?? []) {
const id = testId(spec.file ?? suite.file, [...path, spec.title]);
for (const test of spec.tests ?? []) {
records.push({ id, project: test.projectName ?? null });
}
}
for (const child of suite.suites ?? []) walk(child, path, false);
};
for (const fileSuite of data.suites) walk(fileSuite, [], true);
return records;
}
// Vitest's JSON reporter includes the runtime-expanded title hierarchy.
if (data && Array.isArray(data.testResults)) {
return data.testResults.flatMap((file) =>
(file.assertionResults ?? []).map((assertion) => ({
id: testId(file.name, [...assertion.ancestorTitles, assertion.title]),
project: assertion.projectName ?? file.projectName ?? null
}))
);
}
if (Array.isArray(data)) {
return data.map((entry, i) => {
if (typeof entry === 'string') return { id: entry };
const project = entry.projectName ?? entry.project ?? null;
if (entry.id) return { id: entry.id, project };
if (entry.file && entry.name) {
// Vitest's static listing can retain describe.each title templates.
if (entry.location && /(?:^| > )\$[\w.]+(?: |$)|(?<!%)%[sdifjoOp#]/.test(entry.name)) {
fail(`unexpanded runner title "${entry.name}"; use the JSON execution report with concrete cases`);
}
return { id: testId(entry.file, [entry.name]), project };
}
fail(`inventory entry ${i} has no "id" or "file" and "name"`);
});
}
fail('unrecognized inventory format');
}
const projectKey = (project) => project === '' ? null : project ?? null;
const projectLabel = (project) => project ?? '(unnamed project)';
function projectsById(records) {
const byId = new Map();
for (const { id, project } of records) {
const key = projectKey(project);
const projects = byId.get(id) ?? new Set();
if (projects.has(key)) fail(`ambiguous id "${id}" in ${projectLabel(key)}; give these tests unique titles`);
projects.add(key);
byId.set(id, projects);
}
return byId;
}
function readInventory(paths) {
return projectsById(paths.flatMap((path) => inventoryRecords(readJson(path))));
}
const inventory = readInventory(inventoryPaths);
if (inventory.size === 0) fail('baseline inventory contains no tests');
if (init) {
const tests = [...inventory].map(([id, projects]) => ({
id, projects: [...projects], status: 'todo', events: [], assertions: []
}));
console.log(JSON.stringify({ version: 2, tests }, null, 2));
process.exit(0);
}
const ledger = readJson(ledgerPath);
if (ledger.version !== 2 || !Array.isArray(ledger.tests)) {
fail('expected a version 2 ledger; regenerate from the original runner inventory with --init');
}
const currentPaths = args('current-inventory');
const current = currentPaths.length ? readInventory(currentPaths) : undefined;
function evidenceRecords(data) {
if (Array.isArray(data)) return data;
if (!data || !Array.isArray(data.suites)) fail('unrecognized execution evidence format');
if (data.errors?.length) fail('execution report has runner errors');
const rows = [];
function walk(suite) {
for (const spec of suite.specs ?? []) {
for (const test of spec.tests ?? []) {
const result = test.results?.at(-1);
if (test.expectedStatus !== 'passed' || result?.status !== 'passed') continue;
for (const attachment of result.attachments ?? []) {
if (attachment.name !== 'mbt-parity') continue;
if (typeof attachment.body !== 'string') fail('attach mbt-parity evidence as a JSON body');
try {
rows.push({
...JSON.parse(Buffer.from(attachment.body, 'base64').toString('utf8')),
project: test.projectName ?? null
});
} catch (error) {
fail(`invalid mbt-parity attachment: ${error.message}`);
}
}
}
}
for (const child of suite.suites ?? []) walk(child);
}
for (const suite of data.suites) walk(suite);
return rows;
}
const receipts = new Map();
for (const path of args('evidence')) {
for (const row of evidenceRecords(readJson(path))) {
if (!row || typeof row.id !== 'string' ||
(row.project !== null && typeof row.project !== 'string') ||
(row.kind !== 'replay' && row.kind !== 'control')) {
fail('invalid execution record; expected id, project, and replay or control kind');
}
const key = JSON.stringify([row.id, projectKey(row.project)]);
const cases = receipts.get(key) ?? [];
cases.push(row);
receipts.set(key, cases);
}
}
const byId = new Map();
const errors = [];
for (const [i, entry] of ledger.tests.entries()) {
const where = entry.id ? `"${entry.id}"` : `tests[${i}]`;
if (!entry.id) {
errors.push(`${where}: missing "id"`);
continue;
}
if (byId.has(entry.id)) errors.push(`${where}: duplicate entry`);
byId.set(entry.id, entry);
const projects = Array.isArray(entry.projects) ? entry.projects.map(projectKey) : entry.projects;
if (!Array.isArray(projects) || projects.length === 0 ||
projects.some((project) => project !== null && typeof project !== 'string') ||
new Set(projects).size !== projects.length) {
errors.push(`${where}: expected unique projects from the original runner inventory`);
continue;
}
const baselineProjects = inventory.get(entry.id);
for (const project of projects) {
if (!baselineProjects?.has(project)) {
errors.push(`${where}: missing from baseline in ${projectLabel(project)}`);
}
}
for (const project of baselineProjects ?? []) {
if (!projects.includes(project)) errors.push(`${where}: no ledger entry for baseline project ${projectLabel(project)}`);
}
switch (entry.status) {
case 'mapped': {
// An empty array is valid: the replay checks the initial state.
if (!Array.isArray(entry.events)) {
errors.push(`${where}: mapped entry has no "events" array`);
} else if (entry.events.some((e) => !e || typeof e.type !== 'string')) {
errors.push(`${where}: every event needs a string "type"`);
}
if (!Array.isArray(entry.assertions) || entry.assertions.length === 0) {
errors.push(`${where}: mapped entry has no "assertions"`);
break;
}
for (const [j, a] of entry.assertions.entries()) {
if (!a.legacy) errors.push(`${where}: assertions[${j}] has no "legacy" text`);
if (!a.oracle) errors.push(`${where}: assertions[${j}] has no "oracle"`);
const steps = entry.events?.length ?? 0;
if (!Number.isInteger(a.afterStep) || a.afterStep < 0 || a.afterStep > steps) {
errors.push(`${where}: assertions[${j}].afterStep must be an integer from 0 to ${steps}`);
}
}
for (const project of projects) {
const key = JSON.stringify([entry.id, project]);
const evidence = receipts.get(key) ?? [];
const context = `${where} [${projectLabel(project)}]`;
const replays = evidence.filter((row) => row.kind === 'replay');
if (replays.length !== 1) {
errors.push(replays.length === 0
? `${context}: missing passing replay`
: `${context}: duplicate replay records`);
} else if (replays[0].outcome !== 'passed' || !isDeepStrictEqual(replays[0].events, entry.events)) {
errors.push(`${context}: replay must pass with the ledger events`);
}
for (const [index, assertion] of entry.assertions.entries()) {
const controls = evidence.filter((row) => row.kind === 'control' && row.assertion === index);
if (controls.length !== 1 || controls[0].outcome !== 'diverged' ||
controls[0].afterStep !== assertion.afterStep || controls[0].oracle !== assertion.oracle ||
!isDeepStrictEqual(controls[0].events, entry.events)) {
errors.push(`${context}: control ${index} must diverge at step ${assertion.afterStep} for oracle ${assertion.oracle} using the ledger events`);
}
}
}
break;
}
case 'residual':
if (!entry.reason) errors.push(`${where}: residual entry has no "reason"`);
if (!entry.keptIn) errors.push(`${where}: residual entry has no "keptIn" (where the legacy test still runs)`);
for (const project of projects) {
if (!current?.get(entry.id)?.has(project)) {
errors.push(`${where}: residual test missing from --current-inventory for ${projectLabel(project)}`);
}
}
break;
case 'dropped':
if (!entry.reason) errors.push(`${where}: dropped entry has no "reason"`);
if (!entry.approvedBy) errors.push(`${where}: dropped entry has no "approvedBy" (a person must approve dropping coverage)`);
break;
default:
errors.push(`${where}: status is "${entry.status}"; it must be "mapped", "residual", or "dropped"`);
}
}
const unmapped = [...inventory.keys()].filter((id) => !byId.has(id));
for (const id of unmapped) errors.push(`"${id}": baseline test has no ledger entry`);
const count = (status) => ledger.tests.filter((t) => t.status === status).length;
console.log(
`legacy tests: ${inventory.size}, mapped: ${count('mapped')}, residual: ${count('residual')}, ` +
`dropped: ${count('dropped')}, unmapped: ${unmapped.length}`
);
for (const e of errors) console.log(`error: ${e}`);
console.log(errors.length ? 'parity: INCOMPLETE' : 'parity: complete');
process.exit(errors.length ? 1 : 0);