machina-test
machina-test gives you two things:
- Graph matchers:
toAlwaysReach,toNeverReach, andtoHaveNoUnreachableStatescheck the FSM’s topology. Does a path exist from A to B? 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?”
Install
Section titled “Install”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:
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>.
Matchers
Section titled “Matchers”toHaveNoUnreachableStates()
Section titled “toHaveNoUnreachableStates()”Asserts that every state in the FSM is reachable from initialState.
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.
toAlwaysReach(targetState, { from })
Section titled “toAlwaysReach(targetState, { from })”Asserts that a path exists from from to targetState in the FSM’s top-level graph.
The BFS follows all edges, both "definite" (string shorthand, one return) and "possible" (conditional returns). The matcher checks whether the plumbing exists.
toNeverReach(targetState, { from })
Section titled “toNeverReach(targetState, { from })”Asserts that no path exists from from to targetState. The logical inverse of toAlwaysReach.
.not variants
Section titled “.not variants”Standard Jest/Vitest negation works as expected:
Invalid state names
Section titled “Invalid state names”A typo in a state name produces a normal test failure, and the message lists the available states:
Testing hierarchical FSMs
Section titled “Testing hierarchical FSMs”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().
Why top-level only?
Section titled “Why top-level only?”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
browsingeventually lead to the child’sprocessing?” 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().
Runtime Testing with walkAll
Section titled “Runtime Testing with walkAll”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.
Key concepts
Section titled “Key concepts”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.
Basic usage
Section titled “Basic usage”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.
Payload generators
Section titled “Payload generators”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.
Only inputs that need payloads get generators. Everything else fires with no arguments.
Typed payload generators
Section titled “Typed payload generators”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().
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.
Filtering inputs
Section titled “Filtering inputs”By default, walkAll fires every input it finds. You can narrow the set with include or exclude (mutually exclusive):
Unknown names in include throw immediately, which catches typos before the walks start.
Seed replay
Section titled “Seed replay”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.
In CI, copy the seed from the failing log into your test and the reproduction is deterministic.
BehavioralFsm support
Section titled “BehavioralFsm support”walkAll detects BehavioralFsm instances automatically. Pass a client factory to create a fresh client per walk:
If you don’t provide a client factory, walkAll uses an empty object {}.
WalkFailureError
Section titled “WalkFailureError”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.
Configuration reference
Section titled “Configuration reference”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) |
When to use what
Section titled “When to use what”| 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.
See also
Section titled “See also”- machina-inspect, the graph analysis engine behind the matchers
- ESLint plugin, the same structural checks at lint time in your editor