--- title: Test XState logic description: Test state transitions, actor behavior and async outcomes. --- Test observable behavior by sending an event and checking the resulting snapshot. When the behavior includes I/O, also check the effect at the application boundary. ```ts test('pauses while playing', () => { const player = createActor(playerMachine).start(); player.send({ type: 'play' }); player.send({ type: 'pause' }); expect(player.getSnapshot().matches('paused')).toBe(true); }); ``` Test forbidden behavior too. The events a machine ignores are part of its behavior. ```ts test('does not pause while stopped', () => { const player = createActor(playerMachine).start(); player.send({ type: 'pause' }); expect(player.getSnapshot().matches('stopped')).toBe(true); }); ``` ## Pure transitions When a test only needs the result of a transition, calculate it without starting an actor. `initialTransition(...)` and `transition(...)` run no effects and start no children, so they are the fastest way to cover guards and context updates. Each returns a `[snapshot, actions]` tuple. ```ts test('rejects an email without an @', () => { const [start] = initialTransition(formMachine); const [atEmail] = transition(formMachine, start, { type: 'next', value: 'Ada' }); const [rejected] = transition(formMachine, atEmail, { type: 'next', value: 'nope' }); expect(rejected.value).toBe('email'); expect(rejected.context.email).toBe(''); }); ``` Use experimental [pure system transitions](system-transitions.md) to test invoked/spawned actors, communication and virtual timers in a system snapshot without executing external work. Start an actor when tests need running effects or live subscriptions. ## Replace boundaries with fakes `machine.provide(...)` returns the same machine with different implementations. Swap the actors that reach the network for logic that resolves what the test needs, and leave every state and transition untouched. ```ts import { createAsyncLogic, waitFor } from 'xstate'; const machineWithFakes = orderMachine.provide({ actors: { chargeCard: createAsyncLogic({ run: async () => ({ id: 'ch_1' }) }) } }); test('confirms an order once the card is charged', async () => { const order = createActor(machineWithFakes).start(); order.send({ type: 'submit' }); const snapshot = await waitFor(order, (s) => s.matches('confirmed'), { timeout: 1_000 }); expect(snapshot.context.chargeId).toBe('ch_1'); }); ``` Test the failure path the same way, with fake logic that throws instead of resolving. Always pass a `timeout` to `waitFor(...)`. Without one it waits forever, so a broken machine hangs the test suite instead of failing the test. ## Simulate child completion Use `{ simulate: true }` to control when an invoked child finishes in a test. Invocations start normally, so provide a fake for any child that performs external work. ```ts import { createActor, createAsyncLogic, setup } from 'xstate'; const checkout = setup({ actors: { save: createAsyncLogic({ run: () => new Promise(() => {}) }) } }).createMachine({ initial: 'saving', states: { saving: { invoke: { id: 'save', src: 'save', onDone: { target: 'saved' } } }, saved: {} } }); const actor = createActor(checkout, { simulate: true }).start(); actor.simulate.childDone({ id: 'save', output: 'receipt-1' }); expect(actor.getSnapshot().matches('saved')).toBe(true); ``` `childDone()` requires a running local invocation with that ID. Call it between the child's events. If the child has a validator, XState checks the terminal result before it runs cleanup. It then publishes a `done` snapshot with the supplied output and delivers completion to the parent. The child cannot complete again if its original work finishes later. TypeScript checks the ID and output when the child is known to the machine's types. If custom child logic returns a `done` or `error` snapshot when asked to stop, XState publishes that result. To simulate completion after a restore, enable simulation when creating the actor you persist and when restoring it. XState records invocation identity for embedded registered children of actors with simulation enabled. ## Control time Delays and timeouts do not need real time. Pass a `SimulatedClock` and move it forward yourself. ```ts import { SimulatedClock } from 'xstate'; test('retries after the backoff', () => { const clock = new SimulatedClock(); const request = createActor(requestMachine, { clock }).start(); request.send({ type: 'fail' }); expect(request.getSnapshot().matches('waitingToRetry')).toBe(true); clock.increment(1_000); expect(request.getSnapshot().matches('loading')).toBe(true); }); ``` Use `clock.increment(ms)` to advance by a duration or `clock.set(ms)` to move to an absolute time. Both fire timers that have come due. To test retry behavior independently of its duration, override the named delay with `provide({ delays: { backoff: 0 } })`. After scheduling the retry, call `clock.increment(0)` to fire the timer before reading the snapshot. ## Emitted events Emitted events are delivered to external listeners, so assert on them with `actor.on(...)`. ```ts test('emits when a track starts', () => { const played: string[] = []; const player = createActor(playerMachine).start(); player.on('played', (event) => played.push(event.trackId)); player.send({ type: 'play' }); expect(played).toEqual(['track-1']); }); ``` ## Persistence round-trips A workflow that is restored on every request should be tested the way it runs. Persist, restore and continue: ```ts import { restoreActor } from 'xstate/persist'; test('resumes an order from its persisted snapshot', () => { const first = createActor(orderMachine).start(); first.send({ type: 'submit' }); const persisted = JSON.parse(JSON.stringify(first.getPersistedSnapshot())); first.stop(); const second = restoreActor(orderMachine, persisted).start(); second.send({ type: 'confirm' }); expect(second.getSnapshot().matches('confirmed')).toBe(true); }); ``` Serializing through JSON matters: it catches context that cannot survive a database round-trip, such as a class instance or an open connection. ## What to cover For an order workflow, test the successful payment path and a declined payment retry. For an upload, test completion and cancellation while the request is active. For a form, test one valid submission and each rule that blocks one. ## Next steps - [Look up `waitFor`, `transition` and `SimulatedClock`](utilities.md). - [Swap implementations with `provide(...)`](setup-and-provide.md). - [Read what a snapshot contains](snapshots.md). - [Diagnose a machine that is not behaving](troubleshooting.md). - [Generate tests from a machine with `@xstate/test`](model-based-testing.md). ## Replaying a known event sequence `getPathsFromEvents(logic, events, options)` from `xstate/graph` follows only the supplied event sequence. It can replay finite sequences even when the logic has an unbounded reachable context, such as a counter. It honors `input`, `fromState`, `filterEvents`, `stopWhen`, and `toState`; a filtered or stopped step throws an invalid-transition error. `limit` bounds the number of replayed events. Custom state and event serializers may return any string, including empty strings and names such as `constructor`. `xstate/graph` only generates paths. To run a path against an implementation and compare it with the machine after every step, pass it to `testPaths(machine, { paths, sut })` from `@xstate/test`. See [Model-based testing](model-based-testing.md). `xstate/graph` also exports two static helpers for tools that analyze a machine without running it. `getInitialStateNodes(machine.root)` returns the state nodes of the initial configuration. `getTransitionEntrySet(transition)` returns the state nodes a transition enters, including the default descendants of its targets, the untargeted regions of parallel states, and the ancestors inside its transition domain. History targets resolve to their default targets unless you pass a history value. The transition's `target` and `reenter` are used as given, so pass a transition returned by `getMicrosteps()` to get the entry set of a function transition: ```ts import { getMicrosteps, initialTransition } from 'xstate'; import { getTransitionEntrySet } from 'xstate/graph'; const [snapshot] = initialTransition(machine); const [[, , [taken]]] = getMicrosteps(machine, snapshot, { type: 'SUBMIT' }); getTransitionEntrySet(taken).map((stateNode) => stateNode.id); ```