Skip to content

machina-test

machina-test gives you two things:

  1. Graph matchers: toAlwaysReach, toNeverReach, and toHaveNoUnreachableStates check the FSM’s topology. Does a path exist from A to B?
  2. walkAll: property-based runtime testing. It feeds randomized inputs into a live FSM and checks a rule you define after every transition.

The matchers answer “is the wiring right?” walkAll answers “does it actually work when things happen in a random order?”

npm install --save-dev machina-test
# or
pnpm add -D machina-test

machina >= 8.0.0 is a peer dependency, and the host test runner must be jest >= 29 or vitest >= 1.

Import machina-test in your test files. The import registers the matchers via expect.extend() as a side effect:

import "machina-test";

Or add it to your test runner’s setup file (jest.setup.ts / vitest.setup.ts) to make the matchers available everywhere.

TypeScript users get autocomplete automatically. The package includes ambient type augmentation for both jest.Matchers and Vitest’s Assertion<T>.

Asserts that every state in the FSM is reachable from initialState.

import "machina-test";
import { createFsm } from "machina";

const fsm = createFsm({
    id: "traffic-light",
    initialState: "green",
    states: {
        green: { timeout: "yellow" },
        yellow: { timeout: "red" },
        red: { timeout: "green" },
    },
});

expect(fsm).toHaveNoUnreachableStates(); // passes

This matcher delegates to inspectGraph() and filters for unreachable-state findings. It recurses into child FSM graphs: an orphaned state in a _child FSM fails the assertion on the parent.

Asserts that a path exists from from to targetState in the FSM’s top-level graph.

expect(fsm).toAlwaysReach("delivered", { from: "placed" });

The BFS follows all edges, both "definite" (string shorthand, one return) and "possible" (conditional returns). The matcher checks whether the plumbing exists.

Asserts that no path exists from from to targetState. The logical inverse of toAlwaysReach.

// Terminal states should stay terminal
expect(fsm).toNeverReach("shipped", { from: "cancelled" });

Standard Jest/Vitest negation works as expected:

expect(fsm).not.toAlwaysReach("shipped", { from: "cancelled" }); // no path exists
expect(fsm).not.toNeverReach("delivered", { from: "placed" }); // a path does exist

A typo in a state name produces a normal test failure, and the message lists the available states:

State 'shiped' does not exist in FSM 'order-workflow'.
Available states: placed, validating, processing, shipped, delivered, cancelled, refunded.

toAlwaysReach and toNeverReach operate on the top-level graph only. They do not traverse into _child FSMs.

Test the parent and the child independently by passing each to expect().

import "machina-test";
import { createFsm } from "machina";

// Create the child FSM
const paymentFsm = createFsm({
    id: "payment",
    initialState: "entering-details",
    context: {},
    states: {
        "entering-details": { "submit-payment": "processing" },
        processing: { success: "authorized", failure: "declined" },
        authorized: {},
        declined: { retry: "entering-details" },
    },
});

// Create the parent FSM with the child
const checkoutFsm = createFsm({
    id: "checkout",
    initialState: "browsing",
    context: {},
    states: {
        browsing: { "begin-checkout": "checkout" },
        checkout: {
            _child: paymentFsm,
            "order-placed": "confirmation",
            abandon: "browsing",
        },
        confirmation: { "new-order": "browsing" },
    },
});

// Test the PARENT — only sees browsing, checkout, confirmation
expect(checkoutFsm).toAlwaysReach("confirmation", { from: "browsing" });

// Test the CHILD — only sees entering-details, processing, authorized, declined
expect(paymentFsm).toAlwaysReach("authorized", { from: "entering-details" });
expect(paymentFsm).toNeverReach("entering-details", { from: "authorized" });

Consider a parent with state "checkout" and a child with state "processing". What would toAlwaysReach("processing", { from: "browsing" }) mean?

  • “Does the parent’s graph contain a state called processing?” The answer is no, since only the child declares it.
  • “Can browsing eventually lead to the child’s processing?” That question concerns composite state, which the matchers do not model.

By keeping reachability matchers top-level-only, the answer is always unambiguous: you’re asking about the states in the graph you passed to expect().


The matchers above check graph topology. walkAll runs the FSM with random inputs and checks a rule you define after each transition. When the rule breaks, you get the exact sequence of inputs that caused it, plus a seed that replays the input choices on demand.

Graph matchers cannot evaluate conditional logic. When a handler’s if statement picks the next state, the matchers treat both branches as possible, and they cannot check whether the branch logic is correct. walkAll exercises the real handlers, so it can.

Factory function: a function that creates a fresh FSM on each call. walkAll calls your factory once per walk so each walk starts clean. A shared instance would leak mutations from one walk into the next.

Invariant: a rule that must stay true in every state, such as “the balance never goes negative” or “a user in state admin has a role.” You write it as a function that throws (or returns false) when the rule is violated. walkAll checks the invariant after every transition.

Walk: one complete run through the FSM, from a fresh instance through a sequence of random inputs. One walkAll call runs many walks (default: 100).

Step: one handle() call within a walk. With maxSteps: 20, each walk fires up to 20 random inputs before the next walk starts.

Seed: a number that makes “random” repeatable. A pseudorandom generator produces the same sequence from the same starting number, and that starting number is the seed. The same seed picks the same sequence of input names, which makes failures reproducible.

Payload generator: a function that produces the data to pass with a specific input. Without a generator, an input fires with the input name alone, which is fine for reset and wrong for begin, an input that expects a transfer amount. You configure generators per input name.

import { walkAll } from "machina-test";
import { createAccountTransfer } from "./account-transfer";

const result = walkAll(
    // Factory: each walk gets a fresh FSM
    () => createAccountTransfer(1000),
    {
        walks: 200, // run 200 independent walks
        maxSteps: 20, // up to 20 handle() calls per walk
        seed: 42, // deterministic — same sequence every run
        invariant({ ctx }) {
            const { balance } = ctx as { balance: number };
            if (balance < 0) {
                throw new Error(`balance went negative: ${balance}`);
            }
        },
    }
);

// On success: result.seed and result.walksCompleted
expect(result.walksCompleted).toBe(200);

That’s the minimal case. walkAll auto-extracts the input names from your FSM’s states config, skipping reserved keys like _onEnter, _onExit, _child, and *. Each step it picks one input at random and fires it via handle(), and the invariant runs after every transition.

Without generators, every input fires with no arguments. If your handler expects data (a transfer amount, a user ID, a payload object), you need to tell walkAll how to generate it.

walkAll(() => createAccountTransfer(500), {
    walks: 300,
    maxSteps: 30,
    seed: 7,
    inputs: {
        // "begin" gets a random transfer amount between 0 and 200.
        // "reset" doesn't need a payload — omit it.
        begin: () => Math.floor(Math.random() * 200),
    },
    invariant({ ctx }) {
        const { balance } = ctx as { balance: number };
        if (balance < 0) {
            throw new Error(`balance went negative: ${balance}`);
        }
    },
});

Only inputs that need payloads get generators. Everything else fires with no arguments.

If the factory returns an FSM built with an input payload map, the config changes. The inputs key is gone, and the config requires payloads in its place. You supply one generator per payload-carrying input. Each generator returns that input’s full argument tuple, and walkAll spreads the tuple into handle().

type TrafficLightInputs = {
    timeout: []; // no payload — needs no generator
    emergency: [event: { severity: number }];
};

const makeTypedLight = () => createFsm<TrafficLightInputs>()({ ... });

walkAll(makeTypedLight, {
    walks: 100,
    payloads: {
        // Required. Omitting it — or misspelling "emergency" — is a
        // compile error that names the input.
        emergency: () => [{ severity: Math.floor(Math.random() * 6) }],
    },
    invariant({ state }) {
        // ...
    },
});

The requirement exists because handlers written against a map trust their payloads, because the compiler guarantees them at every application call site. walkAll builds its calls at runtime, outside the compiler’s view. The required payloads key moves the guarantee into your test’s compile step. A forgotten generator fails at the keyboard, before the walk ever runs.

By default, walkAll fires every input it finds. You can narrow the set with include or exclude (mutually exclusive):

// Only fire these two inputs
walkAll(factory, {
    include: ["begin", "reset"],
    invariant,
});

// Fire everything except "admin-override"
walkAll(factory, {
    exclude: ["admin-override"],
    invariant,
});

Unknown names in include throw immediately, which catches typos before the walks start.

When an invariant violation occurs, walkAll throws a WalkFailureError that contains the seed, step, state, and inputSequence fields. Passing that seed back to walkAll replays the same sequence of input choices, and the walk is identical when the payload generators are deterministic. The captured inputSequence records the payloads from the failed run either way.

import { walkAll, WalkFailureError } from "machina-test";

try {
    walkAll(createBuggyFsm, { seed: 1, invariant });
} catch (err) {
    if (err instanceof WalkFailureError) {
        console.log(err.seed); // the seed that found the bug
        console.log(err.step); // which handle() call broke it (1-indexed)
        console.log(err.state); // state at the time of violation
        console.log(err.inputSequence); // full sequence: [{ input, payload }, ...]

        // Replay the exact same walk:
        walkAll(createBuggyFsm, { seed: err.seed, invariant });
        // Same failure, same step, same state.
    }
}

In CI, copy the seed from the failing log into your test and the reproduction is deterministic.

walkAll detects BehavioralFsm instances automatically. Pass a client factory to create a fresh client per walk:

walkAll(() => createBehavioralFsm({/* ... */}), {
    client: () => ({ balance: 1000, transferAmount: 0 }),
    invariant({ ctx }) {
        // ctx is the client object for BehavioralFsm walks
    },
});

If you don’t provide a client factory, walkAll uses an empty object {}.

Thrown when the invariant fails. All properties are readonly:

Property Type Description
seed number The seed that produced this walk
step number Which handle() call caused the violation (1-indexed)
state string State the FSM was in when the invariant broke
previousState string State before the violating transition
compositeState string Full dot-delimited state path (includes child states)
ctx unknown The FSM context (or client for BehavioralFsm) at violation time
inputSequence Array<{ input, payload }> Every input fired up to and including the failing step

The error message itself is human-readable and includes the seed, states, cause, and full input sequence. The format suits CI log output.

interface WalkConfig<TClient extends object = object> {
    /** How many independent walks to run. Default: 100 */
    walks?: number;

    /** Max handle() calls per walk. Default: 50 */
    maxSteps?: number;

    /** Seed for deterministic input selection. Default: random */
    seed?: number;

    /** Only fire these inputs. Mutually exclusive with exclude. */
    include?: string[];

    /** Don't fire these inputs. Mutually exclusive with include. */
    exclude?: string[];

    /** Payload generators keyed by input name. */
    inputs?: Record<string, () => unknown>;

    /** BehavioralFsm client factory. Omit for Fsm walks. */
    client?: () => TClient;

    /** Checked after every transition. Throw or return false to fail. */
    invariant: (args: InvariantArgs) => boolean | void;
}

The InvariantArgs object passed to your invariant:

Property Type Description
state string State the FSM just transitioned TO
previousState string State the FSM transitioned FROM
compositeState string Dot-delimited composite state path
ctx unknown The FSM context or BehavioralFsm client
input string The input name that triggered this transition
payload unknown The payload from the generator, or undefined
step number Which handle() call produced this transition (1-indexed)

Question Tool
Is every state reachable? toHaveNoUnreachableStates()
Does a path exist from state A to state B? toAlwaysReach / toNeverReach
Does the FSM behave correctly under random inputs? walkAll
Is there a conditional logic bug the graph can’t see? walkAll
Will the guard in _onEnter actually prevent bad transitions? walkAll

The matchers and walkAll are complementary. Use matchers for fast structural sanity checks. Use walkAll when your FSM has handler logic (conditionals, context mutations, guards) that matters.