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
Rules:
@xstate/test 2.x requires xstate 6. With no xstate, propose
@xstate/test@beta xstate@beta fast-check as dev dependencies and say they
are betas. With xstate 5, ask before upgrading, or put the model tests in
a separate workspace package with xstate@beta.
Read node_modules/@xstate/test/README.md (API) and
node_modules/xstate/docs/model-based-testing.md. Write the machine in v6
syntax (node_modules/xstate/docs/agents.md or the xstate-v6 skill). If
the packages are not installed, read the tarballs:
dir=$(mktemp -d) && cd "$dir" && npm pack @xstate/test@beta xstate@beta && for f in *.tgz; do mkdir "${f%.tgz}" && tar xzf "$f" -C "${f%.tgz}"; doneUse testPaths in CI (@xstate/test/paths needs no fast-check). Add
propertyTest with until when payloads, ordering, or timing matter, or
the graph is too large to enumerate. Use createPlaywrightSut for web
pages.
Known issues in 2.0.0-beta.3 (check for a fixed release first):
failures works only with testPaths from @xstate/test (needs
fast-check). From @xstate/test/paths it throws failureStore.load is not a function.@playwright/test 1.64+, createPlaywrightSut(page) fails to
type-check (tracing.start() returns Promise<Disposable>). Pass
page as Page & PlaywrightPage. Playwright does not type-check tests, so
run tsc --noEmit.E: ({ context }) => ...) has one coverage id for
all of its branches, so transitions: 1 passes when one branch ran. Give
each branch a distinct target state and gate on stateNodes: 1, or check
the branches in the coverage viewer.'existing' to string) and fail createMachine overloads. Add
as const.meta: types<{ requirements?: string | string[] }>() in schemas to use
meta.requirements. Write each target literally in the transition, not
in a helper, and start a transition function with its if, so the diagram
draws each branch. Check that it does before trusting viewer counts.projectModel(snapshot) and read() return the same shape, containing
only what the UI shows. If the UI depends on the pointer (hover), move the
pointer to a neutral spot after every event except hover events. read()
uses non-waiting calls (count, allTextContents), so a missing element
is an observation, not a timeout. Keep transient UI such as toasts out of
the projection, or make sure settle() returns before it disappears.create() (Playwright: reset), waits in settle(),
and stubs the network per event case with mocks or outcomes. Every
path must start from the same app state. Decide what the reset covers
(browser storage, server data, inboxes or other side channels the test
reads) and how: fresh data with unique values per path, or a restored
snapshot. For history, storage, and session tests, use a
fresh browser context per path.
Close it in dispose. Wait for an observable outcome or app readiness
signal before comparing an observation.cases ({ username: 'empty' },
{ username: 'tooLong' }) and let the SUT supply concrete values, such as
the path's own user data.stopWhen or serializeState. Keep context
that changes enabled transitions, observations, or required history. Count
paths before attaching a browser. testPaths without a SUT returns
coverage and results with zero SUT comparisons. Use the path count to
size the browser test timeout.assertTestCoverage(coverage, { transitions: 1, stateNodes: 1, unknown: 'fail' }).
Use unknown: 'fail' in coverage-based propertyTest stop conditions too,
then assert coverage after the run. With older packages, explicitly check
that coverage.transitions.unknown and coverage.stateNodes.unknown
are empty. Check required named event cases and require positive
coverage.sutComparisons when using projections. On versions that support
it, set sutComparisons: 1 in assertTestCoverage. Use failures: true
through the main package entry point.testDir so they use the
same webServer and projects.Generated paths may skip a legacy test's sequence, and the projection may miss what it asserted. Track each legacy test in a ledger. Format and templates: references/parity-ledger.md.
Inventory with each runner that holds end-to-end tests, not by reading files, before adding model test files. Write one file per runner, and pass file filters to replace a subset:
npx playwright test --list --reporter=json > e2e-inventory.playwright.json
npx vitest list e2e --json=e2e-inventory.vitest.jsonCheck that every browser project and parameterized case is present. If a
Vitest listing retains titles such as $name, run the selected legacy
suite with vitest run --reporter=json --outputFile=e2e-inventory.vitest.json
and use that report. For runners without a supported inventory format,
export the expanded cases as { id, project } records.
node <skill-dir>/scripts/parity-check.mjs --inventory e2e-inventory.playwright.json --inventory e2e-inventory.vitest.json --init > e2e-parity.json.
Keep those original inventories. The ledger records every browser or
runner project per case. Write the model test after generating the ledger.
For each test, read the body, hooks, fixtures, and page objects. Record
its user actions as events (setup goes in input, reset, or mocks),
each assertion with afterStep and its oracle, and a status:
Preserve the action channel, such as a hydrated form or a native form POST.
mapped: covered by the model test.residual: the model cannot express it; the legacy test stays (keptIn).dropped: only with the user's approval (approvedBy).Extend the model or projection until every assertion has an oracle. Never
weaken an assertion. A test with no expect asserts that its actions
succeed: quote the action as legacy and use the oracle that fails when
the action has no effect. One event can group a fill and its submit when
no assertion falls between them.
Replay each mapped entry with
testPaths(machine, { fromEvents, strictReplay: true }). For intentional
no-ops, use a scoped strictReplay.allowUnhandled predicate. If the
installed package lacks strict replay, verify event acceptance explicitly
during replay and allow only the documented no-ops. On
Path diverged, fix the model or adapter, not the ledger. The default
Playwright oracles also fail on console errors and 4xx responses. If the
legacy tests pass despite existing ones, set oracles explicitly (for
example { pageError: true, http: 500, unhandledRejection: true }) and
report those errors.
Add generated coverage (pathGenerator: 'edges') with assertTestCoverage.
If setup dominates browser time, plan fewer paths
with cover.requirements. Keep the same coverage gates and exact replays.
For each legacy assertion, change observable application output in the app, mock, or fixture. Confirm the replay first diverges at the assertion's step and that the mapped oracle detects the changed value. Mark the test residual when the assertion cannot be tested this way. Revert each fault.
Collect execution evidence for every mapped case and project. Run
node <skill-dir>/scripts/parity-check.mjs --inventory <original inventory> --ledger e2e-parity.json --evidence <run report>.
Repeat --inventory and --evidence as needed. If any test is residual,
also pass a fresh runner listing with --current-inventory. Require exit
0 before replacing tests. See the evidence format.
If the project can collect code coverage (Istanbul, or V8 through
page.coverage), run both suites with it. Code only the legacy suite
executes is a gap.
Run both suites in CI under the legacy suite's browser projects. After a green run and parity check, delete mapped tests, keep residual ones, and commit the ledger and original inventories. Without CI access, keep the legacy tests and report.
Usually residual: screenshots, accessibility audits, exact request payloads, analytics, performance, copy not in the projection, multiple tabs or users.
visualize_machine with { machine: "<model source>", format: "xstate" }.
In a terminal, add presentation: "unicode" and show the diagram in a code
block.visualize_machines call with all of them (up to 20),
each with a stable machine id. Reuse the returned workspaceId to add or
update models.open_stately_editor with the trace's events as
session.simulation.Copy links exactly. Without a Stately connection, say how to sign in (Claude
Code: /mcp, authenticate stately; Codex: codex mcp login stately).
scripts/coverage-viewer.mjs shows the model in a Stately embed and colors
state nodes and transitions green when a run covers them and red when a run
reports them uncovered. Stately draws each branch of a function transition as
its own edge, and coverage ids do not say which branch ran, so the viewer
matches each reported step to the branch whose target it reached.
node <skill-dir>/scripts/coverage-viewer.mjs --machine <model file>The viewer needs @statelyai/sdk: install it with npm i -D @statelyai/sdk,
or pass --sdk <dist dir>. It listens on 127.0.0.1 only. Open
http://127.0.0.1:5173. The hosted editor needs sign-in or
STATELY_API_KEY; --viz <url> selects another editor.
Report each run from the tests, then run them with
MBT_VIEWER_URL=http://127.0.0.1:5173:
import { test } from '@playwright/test';
import { testCoverageToJSON } from '@xstate/test/paths';
type Result = {
coverage: Parameters<typeof testCoverageToJSON>[0];
results: readonly {
path: { steps: readonly { event: { type: string }; state: { value: unknown } }[] };
}[];
};
export async function reportCoverage({ coverage, results }: Result) {
const url = process.env.MBT_VIEWER_URL;
if (!url) return;
await fetch(`${url}/coverage`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
coverage: testCoverageToJSON(coverage),
paths: results.map(({ path }) =>
path.steps.map((step) => ({ event: step.event.type, value: step.state.value }))
),
label: test.info().title
})
}).catch(() => {});
}Call reportCoverage(result) with the result of each testPaths.
Follow the installed README's migration section. Keep the old tests until the new ones pass with equal or higher state node coverage.
Model files and Stately links (or a viewer screenshot), test command and result, coverage summary. For a replacement, add the parity check output, the negative controls that ran, and the residual tests.