CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

statelyai/model-based-testing

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.

Quality

100%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Medium

Suggest reviewing before use

Overview
Quality
Evals
Security
Files

parity-ledger.mdreferences/

Parity ledger

e2e-parity.json, checked against the test inventory by scripts/parity-check.mjs.

{
  "version": 2,
  "tests": [
    {
      "id": "e2e/login.spec.ts > shows an error for a wrong password, then recovers",
      "projects": ["chromium", "firefox", "webkit"],
      "status": "mapped",
      "events": [
        { "type": "FILL_EMAIL", "value": "ada@example.com" },
        { "type": "FILL_PASSWORD", "value": "nope" },
        { "type": "SUBMIT" },
        { "type": "FILL_PASSWORD", "value": "hunter2" },
        { "type": "SUBMIT" }
      ],
      "assertions": [
        { "legacy": "expect(page.getByRole('alert')).toHaveText('Wrong password')", "afterStep": 3, "oracle": "projectModel.error" },
        { "legacy": "expect(page).toHaveURL('/welcome')", "afterStep": 5, "oracle": "projectModel.screen" }
      ]
    },
    {
      "id": "e2e/login.spec.ts > login form matches visual snapshot",
      "projects": ["chromium", "firefox", "webkit"],
      "status": "residual",
      "reason": "Screenshot comparison.",
      "keptIn": "e2e/login.spec.ts"
    },
    {
      "id": "e2e/login.spec.ts > logs in (old flow)",
      "projects": ["chromium", "firefox", "webkit"],
      "status": "dropped",
      "reason": "Duplicates 'logs in with valid credentials'.",
      "approvedBy": "Ada Lovelace"
    }
  ]
}
FieldRequired forValue
idall<file> > <describe titles> > <test title>, as the inventory prints it (Playwright paths are relative to testDir)
projectsallOriginal runner project names. Use null for an unnamed project.
statusallmapped, residual, or dropped (--init writes todo, which fails)
eventsmappedModel events in legacy order, with the payloads or case kinds the test used. [] checks only the initial state
assertions[].legacymappedThe legacy assertion, quoted
assertions[].afterStepmappedEvents sent before the assertion; 0 is the initial state
assertions[].oraclemappedprojectModel.<key>, states.<state> (also server-side checks), invariant:<name>, check:<name>, or setup:<name> (a precondition reset or an event creates)
reasonresidual, droppedWhy the model does not cover it
keptInresidualWhere the legacy test still runs
approvedBydroppedThe person who approved dropping it

For generated data (faker, random ids), record the value the test used and make the model accept any generated value.

Vitest

import { test } from 'vitest';
import type { EventFrom } from 'xstate';
import { testPaths } from '@xstate/test/paths';
import { loginMachine } from './login.machine';
import { sut } from './login.sut';
import ledger from './e2e-parity.json';

type Event = EventFrom<typeof loginMachine>;

for (const entry of ledger.tests.filter((t) => t.status === 'mapped')) {
  test(`parity: ${entry.id}`, async () => {
    await testPaths(loginMachine, {
      fromEvents: entry.events as Event[],
      strictReplay: true,
      sut
    });
  });
}

Playwright

import { test } from '@playwright/test';
import type { EventFrom } from 'xstate';
import { testPaths } from '@xstate/test/paths';
import { createPlaywrightSut } from '@xstate/test/playwright';
import { loginMachine } from './login.machine';
import { loginPage } from './login.page';
import ledger from './e2e-parity.json' with { type: 'json' };

type Event = EventFrom<typeof loginMachine>;

for (const entry of ledger.tests.filter((t) => t.status === 'mapped')) {
  test(`parity: ${entry.id}`, async ({ page }, testInfo) => {
    await testPaths(loginMachine, {
      fromEvents: entry.events as Event[],
      strictReplay: true,
      sut: createPlaywrightSut(page, { ...loginPage, testInfo })
    });
    await testInfo.attach('mbt-parity', {
      body: JSON.stringify({
        id: entry.id, kind: 'replay', outcome: 'passed', events: entry.events
      }),
      contentType: 'application/json'
    });
  });
}

loginPage holds reset, events, read, projectModel, and mocks. Share it with the generated test so both observe the page the same way.

Execution evidence

Keep the original runner listings and pass them as --inventory. If a Vitest run report omits project names, run each named project separately and set projectName on its file records from the project filter used for that run. Use null for a runner without named projects.

Collect fresh execution evidence in the same browser or runner projects. Pass Playwright's JSON run report to --evidence, with an mbt-parity attachment on each passing replay and control. The checker reads the project from the test result. For other runners, have the test harness emit the same records as a JSON array, with a project field on every record.

For each assertion, record the zero-based assertion index only after the control proves the named oracle detected a change at the specified event position. A divergence involving a different field or an earlier step fails the control test. For an event-only projection replay, use the failure trace to count delivered user events. An initial observation has position zero. The fixture's failedAt counts stable observations from one.

{
  "id": "e2e/login.spec.ts > shows an error for a wrong password, then recovers",
  "kind": "control",
  "outcome": "diverged",
  "assertion": 0,
  "events": [
    { "type": "FILL_EMAIL", "value": "ada@example.com" },
    { "type": "FILL_PASSWORD", "value": "nope" },
    { "type": "SUBMIT" },
    { "type": "FILL_PASSWORD", "value": "hunter2" },
    { "type": "SUBMIT" }
  ],
  "afterStep": 3,
  "oracle": "projectModel.error"
}

If any case is residual, list the remaining tests with the runner and pass that listing as --current-inventory. Run the check before removing mapped cases and again against the post-removal listing for residual cases. Reinitialize version 1 ledgers from the preserved original reports and copy each existing mapping into its version 2 entry.

Fresh browser contexts

Use a fresh context for each SUT session when paths depend on browser history, storage, permissions, or authentication state. Pass the original project's context settings, including viewport and storage state when used. Reset backend data separately. This wrapper also closes the context if adapter setup throws.

import type { Browser, BrowserContextOptions, Page } from '@playwright/test';
import { createPlaywrightSut } from '@xstate/test/playwright';
import { loginPage } from './login.page';

const pageSut = (page: Page) => createPlaywrightSut(page, loginPage);

function freshSut(browser: Browser, options: BrowserContextOptions): ReturnType<typeof pageSut> {
  return {
    projectModel: loginPage.projectModel,
    async create(input) {
      const context = await browser.newContext(options);
      try {
        const session = await pageSut(await context.newPage()).create(input);
        return {
          ...session,
          async dispose(outcome) {
            try {
              await session.dispose?.(outcome);
            } finally {
              await context.close();
            }
          }
        };
      } catch (error) {
        await context.close();
        throw error;
      }
    }
  };
}

Plan fewer paths

Use cover.requirements when starting a browser, seeding a fixture, or resetting a backend dominates runtime. Name each required behavior and use an array of step predicates for a sequence. Run exact legacy replays separately. Measure the planned path count and check the required coverage again after running against the app.

const { results, coverage } = await testPaths(commentMachine, {
  sut,
  cover: {
    maxPaths: 2,
    maxStepsPerPath: 4,
    requirements: {
      recovery: [
        ({ event }) => event.type === 'INVALID',
        ({ event, snapshot }) => event.type === 'VALID' && snapshot.matches('recovered'),
        ({ event }) => event.type === 'RELOAD'
      ],
      directPublish: ({ event, snapshot }) =>
        event.type === 'VALID' && snapshot.matches('published')
    }
  }
});
assertTestCoverage(coverage, { requirements: 1, sutComparisons: 1 });
console.log({ paths: results.length, comparisons: coverage.sutComparisons });

This example covers two named behaviors. If the original campaign also requires other transitions, name them in the plan and assert the same transition coverage. With an older package, check coverage.sutComparisons directly.

LICENSE

README.md

SKILL.md

tile.json