Unit testing recipes
Every recipe on this page tests a piece of input-actions code without mounting a component. If you find yourself reaching for render() to test something here, the test belongs on the component testing page — not this one.
Selectors and prepareUIData
Section titled “Selectors and prepareUIData”Pure state → props functions. Test by passing a state literal and asserting on the output.
import type { AppState } from './types';
export interface CartLineView { index: number; text: string; qty: number; subtotalCents: number;}
export function prepareCart(state: AppState) { const lines: CartLineView[] = state.cart.lines.map((line, index) => { const item = state.catalog[line.itemId]; return { index, text: item.name, qty: line.qty, subtotalCents: item.price * line.qty, }; }); return { lines, subtotalCents: lines.reduce((sum, l) => sum + l.subtotalCents, 0), isEmpty: lines.length === 0, };}import { describe, expect, test } from 'vitest';import { prepareCart } from './prepare';
const baseState = { catalog: { tee: { id: 'tee', name: 'T-shirt', price: 2500 } }, cart: { lines: [{ itemId: 'tee', qty: 2 }] },} as any;
describe('prepareCart', () => { test('produces line views with subtotals', () => { const view = prepareCart(baseState); expect(view.lines).toEqual([ { index: 0, text: 'T-shirt', qty: 2, subtotalCents: 5000 }, ]); expect(view.subtotalCents).toBe(5000); expect(view.isEmpty).toBe(false); });
test('isEmpty when no lines', () => { expect(prepareCart({ ...baseState, cart: { lines: [] } }).isEmpty).toBe(true); });});No React. No hooks. The exact same function the component reads via useStore((s) => prepareCart(s)) is exercised directly. Edge cases — empty cart, missing catalog entries, large quantities — get the same shape of test.
Predicate validators
Section titled “Predicate validators”Same idea, smaller. Anything used as a state-machine invariants or a UI gate is a function from state to boolean (or error string).
// src/machine.ts (excerpt)export function isAddressValid(state: AppState): boolean { const a = state.address; return !!(a.name.trim() && a.line1.trim() && a.city.trim() && a.postalCode.trim());}test('isAddressValid requires all four fields', () => { const full = { name: 'Ada', line1: '1 Lovelace Ln', city: 'London', postalCode: 'W1' }; expect(isAddressValid({ address: full } as any)).toBe(true); expect(isAddressValid({ address: { ...full, line1: '' } } as any)).toBe(false); expect(isAddressValid({ address: { ...full, name: ' ' } } as any)).toBe(false);});Trimming, edge cases, locale-specific fields — all caught here, not by mounting the form and trying invalid input through the DOM.
Action data
Section titled “Action data”Action tuples are values. You can compare them with toEqual.
Static binding data
Section titled “Static binding data”import { describe, expect, test } from 'vitest';import { appBindings } from './bindings';
test('composer.draft writes draft from the input event', () => { expect(appBindings['composer.draft']).toEqual({ onChange: [['action/save', ['draft'], 'event/target.value']], });});Most static binding entries are checked this way. If a binding is later refactored to fire two actions instead of one, this test catches the change and forces you to think about whether it was intentional.
Factory binding output
Section titled “Factory binding output”For factory bindings, call the function with sample params and assert on the returned tuple list.
import { appBindings } from './bindings';
test('todo-item.onToggle fires for the given id', () => { // The entry is the union of EventBindingMap and machine-rooted; for // flat entries the values are ActionBinding (Action[] | factory). const factory = appBindings['todo-item'].onToggle as (p: { id: string }) => unknown;
expect(factory({ id: 'abc' })).toEqual([ ['action/toggle', ['todos', 'abc', 'done']], ]);});The same factory might branch on params (e.g., the cart onDecrement removes the line when qty hits 0). Test each branch.
test('cart.line.onDecrement removes the line when qty would hit 0', () => { const factory = appBindings['cart.line'].onDecrement as Function; const allLines = [{ itemId: 'tee', qty: 1 }, { itemId: 'mug', qty: 2 }];
const result = factory({ index: 0, currentQty: 1, allLines }); // Splices index 0, keeping the second line. expect(result).toEqual([ ['action/save', ['cart', 'lines'], [{ itemId: 'mug', qty: 2 }]], ]);});applyAction — the sync reducer
Section titled “applyAction — the sync reducer”applyAction(state, action, initial) is exported from @input-actions/core. It’s the same pure function every adapter routes sync actions through (ADR 0015). Test app-specific state transitions by calling it directly.
import { describe, expect, test } from 'vitest';import { applyAction, type Action } from '@input-actions/core';
const initial = { count: 0, user: { name: '' }, todos: [] as string[] };
describe('applyAction', () => { test('action/save sets a nested path', () => { const next = applyAction( initial, ['action/save', ['user', 'name'], 'Ada'], initial, ); expect(next).toEqual({ ...initial, user: { name: 'Ada' } }); });
test('action/increment adds to a number', () => { expect(applyAction(initial, ['action/increment', ['count']], initial)) .toEqual({ ...initial, count: 1 }); });
test('action/push appends to an array', () => { expect(applyAction(initial, ['action/push', ['todos'], 'buy milk'], initial)) .toEqual({ ...initial, todos: ['buy milk'] }); });
test('action/batch applies in order', () => { const next = applyAction( initial, ['action/batch', [ ['action/save', ['user', 'name'], 'Ada'], ['action/increment', ['count'], 5], ]] as Action, initial, ); expect(next).toEqual({ ...initial, user: { name: 'Ada' }, count: 5 }); });
test('action/reset restores initial when called without a path', () => { const modified = { ...initial, count: 42, user: { name: 'Bob' } }; expect(applyAction(modified, ['action/reset'], initial)).toEqual(initial); });});This is the reducer-level test that’s painful to write in plain React (because there is no reducer). Every sync action variant gets exercised here without a store, adapter, or component.
State machine validator
Section titled “State machine validator”StateMachineValidator is constructed from a list of machine definitions and exposes pure methods: canTransition, validateTransition, getAllowedTransitions.
import { describe, expect, test } from 'vitest';import { StateMachineValidator, type StateMachineDefinition } from '@input-actions/core';
const traffic: StateMachineDefinition = { name: 'light', initialState: 'red', states: { red: { allowedTransitions: ['green'] }, green: { allowedTransitions: ['yellow'] }, yellow: { allowedTransitions: ['red'] }, },};
const validator = new StateMachineValidator([traffic]);
describe('traffic light FSM', () => { test('red → green is allowed', () => { const r = validator.validateTransition('light', {}, 'red', 'green'); expect(r.allowed).toBe(true); expect(r.newMode).toBe('green'); });
test('red → yellow is rejected', () => { const r = validator.validateTransition('light', {}, 'red', 'yellow'); expect(r.allowed).toBe(false); expect(r.error).toMatch(/Invalid transition/); });
test('getAllowedTransitions reflects the current mode', () => { expect(validator.getAllowedTransitions('light', 'red')).toEqual(['green']); expect(validator.getAllowedTransitions('light', 'green')).toEqual(['yellow']); });});Testing invariants
Section titled “Testing invariants”When a machine state has an invariants predicate, the validator runs it against the current state at transition time. Pass different states to verify each branch:
const checkout: StateMachineDefinition = { name: 'checkout', initialState: 'cart', states: { cart: { allowedTransitions: ['address'] }, address: { allowedTransitions: ['shipping'], invariants: (state: any) => state.cart.lines.length > 0 ? null : 'Cart is empty', }, shipping: { allowedTransitions: [] }, },};
const v = new StateMachineValidator([checkout]);
test('cart → address blocked when cart is empty', () => { const r = v.validateTransition( 'checkout', { cart: { lines: [] } }, 'cart', 'address', ); expect(r.allowed).toBe(false); expect(r.error).toBe('State invariant violation: Cart is empty');});
test('cart → address allowed when cart has items', () => { const r = v.validateTransition( 'checkout', { cart: { lines: [{ itemId: 'tee', qty: 1 }] } }, 'cart', 'address', ); expect(r.allowed).toBe(true);});Testing onEnter / onExit side-effects
Section titled “Testing onEnter / onExit side-effects”validateTransition returns the sideEffects array (the source state’s onExit followed by the target’s onEnter). Assert on the literal actions:
const wizard: StateMachineDefinition = { name: 'wizard', initialState: 'step1', states: { step1: { allowedTransitions: ['step2'], onExit: [['action/save', ['exited'], true]], }, step2: { allowedTransitions: [], onEnter: [['action/save', ['entered'], true]], }, },};const v = new StateMachineValidator([wizard]);
test('step1 → step2 fires onExit then onEnter', () => { const r = v.validateTransition('wizard', {}, 'step1', 'step2'); expect(r.sideEffects).toEqual([ ['action/save', ['exited'], true], ['action/save', ['entered'], true], ]);});The hooks are data. You compare them with toEqual — no need to dispatch and check that state changed.
Async handlers
Section titled “Async handlers”Handlers passed to asyncHandlers are plain async functions. The library only adds a { signal, getState } argument at the end. Test them directly, passing a signal and, if the handler reads state, a getState that returns the state you want to test with.
import { describe, expect, test, vi } from 'vitest';
const submitForm = async ( data: { username: string }, { signal }: { signal: AbortSignal },) => { if (data.username === 'error') throw new Error('not allowed'); return { ok: true, id: 'abc' };};
describe('submitForm handler', () => { test('returns success for a valid payload', async () => { const ctrl = new AbortController(); const result = await submitForm({ username: 'ada' }, { signal: ctrl.signal }); expect(result).toEqual({ ok: true, id: 'abc' }); });
test('throws for a forbidden username', async () => { const ctrl = new AbortController(); await expect( submitForm({ username: 'error' }, { signal: ctrl.signal }), ).rejects.toThrow('not allowed'); });});Handlers that close over the store
Section titled “Handlers that close over the store”If your handler is built by a factory (createAsyncHandlers(store) in the chat and checkout examples), pass a mock store:
import { createSimpleStore } from '@input-actions/core';import { createAsyncHandlers } from './handlers';
test('flushOutbox drains the queued messages', async () => { const store = createSimpleStore({ me: { id: 'me', name: 'You' }, outbox: [ { tempId: '1', channelId: 'general', text: 'hi', enqueuedAt: 0 }, { tempId: '2', channelId: 'general', text: 'there', enqueuedAt: 0 }, ], _async: {}, });
const handlers = createAsyncHandlers(store as any); const count = await handlers.flushOutbox({ signal: new AbortController().signal });
expect(count).toBe(2); // The handler dispatched the cleanup itself — outbox is empty now. expect((store.getState() as any).outbox).toEqual([]);});You’re testing the handler’s contract: given a state, what does it return and what does it dispatch? No <StoreProvider>, no render, no asynchronous component updates to chase.
Cancellation
Section titled “Cancellation”Handlers receive an AbortSignal. Test that they honour it:
test('searchMessages aborts when the signal fires', async () => { const ctrl = new AbortController(); const pending = searchMessages('query', [], ctrl.signal); ctrl.abort(); await expect(pending).rejects.toThrow();});Most of the cancellation work is the library’s job (the executor wires the AbortController per dispatch); your handler just needs to read signal.aborted or pass signal through to fetch.
What you’ll typically have
Section titled “What you’ll typically have”A balanced suite for an input-actions feature might look like:
| File | Tests | Lines |
|---|---|---|
prepare.test.ts | derivations | many |
machine.test.ts | validator transitions + invariants | several |
handlers.test.ts | handler returns + dispatches | several |
bindings.test.ts | binding factory outputs | few |
Component.test.tsx | rendering + dispatch wiring | smallest |
The pyramid is flipped from typical React: the broadest tests are the cheapest.
Where to go next
Section titled “Where to go next”- Component testing recipes — for the small layer of tests that still need rendering.
- Action types reference — the action vocabulary you’ll be asserting on in tests.
- Machine actions concept — the FSM features the validator tests exercise.