Component testing recipes
For the small layer of tests that still need to run a component — to verify wiring, subscriptions, and full flows. The recipes below mirror the patterns the library uses in its own test suite (packages/core/src/**/*.test.{ts,tsx}).
useLocalActions with renderHook
Section titled “useLocalActions with renderHook”For component-local state. No provider needed; useLocalActions doesn’t read context.
import { act, renderHook } from '@testing-library/react';import { describe, expect, test } from 'vitest';import { useLocalActions } from '@input-actions/core';
describe('useLocalActions', () => { test('dispatch updates state', () => { const { result } = renderHook(() => useLocalActions({ count: 0, name: '' }), );
act(() => { result.current.dispatch(['action/increment', ['count']]); }); expect(result.current.state.count).toBe(1);
act(() => { result.current.dispatch(['action/save', ['name'], 'Ada']); }); expect(result.current.state.name).toBe('Ada'); });});renderHook returns a result object that re-reads the hook’s return value after each act(() => …). dispatch is the low-level form — for tests, it’s slightly more direct than actions(...) (which returns an event handler).
Async with the local hook
Section titled “Async with the local hook”The _async slice tracks lifecycle automatically. Use the deferred-handler pattern so the test controls when the promise resolves — no setTimeout, no real network.
import { vi } from 'vitest';
function deferredHandler() { const resolvers: Array<(v: any) => void> = []; const signals: AbortSignal[] = []; const fn = vi.fn().mockImplementation((...args: any[]) => { const opts = args[args.length - 1] as { signal: AbortSignal }; signals.push(opts.signal); return new Promise((res, rej) => { resolvers.push(res); opts.signal.addEventListener('abort', () => rej(new Error('aborted'))); }); }); return { fn, resolvers, signals };}
test('async-prevent blocks duplicates while in flight', async () => { const h = deferredHandler(); const { result } = renderHook(() => useLocalActions({}, { fetchUser: h.fn }), );
act(() => { result.current.dispatch(['action/async-prevent', 'op', 'fetchUser']); }); expect(h.fn).toHaveBeenCalledTimes(1); expect(result.current.isLoading('op')).toBe(true);
// Second dispatch while loading — blocked. act(() => { result.current.dispatch(['action/async-prevent', 'op', 'fetchUser']); }); expect(h.fn).toHaveBeenCalledTimes(1);
// Resolve and check transition to success. await act(async () => { h.resolvers[0]('done'); }); expect(result.current.isLoading('op')).toBe(false); expect(result.current.getData('op')).toBe('done');});The deferred-handler factory is in packages/core/src/hooks/useLocalActions.test.ts and is used identically by the StoreProvider tests. It’s the canonical pattern for async tests — no fake timers, no global mocks, just promise control.
act with async resolvers
Section titled “act with async resolvers”Two patterns to know:
// Synchronous dispatch — wrap in plain act().act(() => { result.current.dispatch(['action/save', ['x'], 1]);});
// Promise resolution in tests — wrap in async act and await it.// React commits state updates that result from the resolution; without// awaiting, the test sees stale state.await act(async () => { h.resolvers[0]('done');});StoreProvider with render
Section titled “StoreProvider with render”For global state. Build the store, wrap with the provider, render the hook or a small consumer.
import React from 'react';import { renderHook, act } from '@testing-library/react';import { describe, expect, test } from 'vitest';import { StoreProvider, createSimpleStore, useDispatch, useStore,} from '@input-actions/core';
function makeWrapper( store: ReturnType<typeof createSimpleStore>, asyncHandlers: Record<string, any> = {},) { return ({ children }: { children: React.ReactNode }) => ( <StoreProvider store={store} asyncHandlers={asyncHandlers}> {children} </StoreProvider> );}
const useStoreApi = () => ({ state: useStore<any>(), dispatch: useDispatch(),});
describe('StoreProvider', () => { test('sync dispatch updates state', () => { const store = createSimpleStore({ count: 0 }); const { result } = renderHook(useStoreApi, { wrapper: makeWrapper(store), });
act(() => { result.current.dispatch(['action/increment', ['count']]); }); expect(result.current.state.count).toBe(1); });});The makeWrapper helper takes a store (and optionally handlers + machines) and produces the wrapper component renderHook expects. Reuse it across tests.
Selector subscriptions — verifying re-render scope
Section titled “Selector subscriptions — verifying re-render scope”A common worry: “does this component re-render when unrelated state changes?” Test it.
test('selector re-renders only when the selected slice changes', () => { const store = createSimpleStore({ a: 0, b: 0 }); const wrapper = makeWrapper(store);
let renderCount = 0; const { result } = renderHook( () => { renderCount++; return useStore<{ a: number; b: number }, number>((s) => s.a); }, { wrapper }, );
expect(renderCount).toBe(1);
// Unrelated slice — no re-render. act(() => store.dispatch(['action/save', ['b'], 99])); expect(renderCount).toBe(1); expect(result.current).toBe(0);
// Selected slice — re-renders. act(() => store.dispatch(['action/save', ['a'], 42])); expect(renderCount).toBe(2); expect(result.current).toBe(42);});The pattern (from the library’s own test suite): increment a counter inside the rendered hook, dispatch to an unrelated slice, assert the counter didn’t move. If it did, your selector is reading too much.
State machines in the provider
Section titled “State machines in the provider”import type { StateMachineDefinition } from '@input-actions/core';
const trafficLight: StateMachineDefinition = { name: 'light', initialState: 'red', states: { red: { allowedTransitions: ['green'] }, green: { allowedTransitions: ['yellow'] }, yellow: { allowedTransitions: ['red'] }, },};
function wrap(store: any, machines: StateMachineDefinition[] = []) { return ({ children }: { children: React.ReactNode }) => ( <StoreProvider store={store} stateMachines={machines}> {children} </StoreProvider> );}
test('valid transition updates the mode', () => { const store = createSimpleStore({ light: { mode: 'red' }, _async: {} }); const { result } = renderHook(useStoreApi, { wrapper: wrap(store, [trafficLight]), });
act(() => { result.current.dispatch(['machine/transition', 'light', 'green']); }); expect(result.current.state.light.mode).toBe('green');});
test('invalid transition leaves mode and writes error', () => { const store = createSimpleStore({ light: { mode: 'red' }, _async: {} }); const { result } = renderHook(useStoreApi, { wrapper: wrap(store, [trafficLight]), });
act(() => { // red → yellow is not allowed result.current.dispatch(['machine/transition', 'light', 'yellow']); }); expect(result.current.state.light.mode).toBe('red'); expect(result.current.state.light.error).toMatch(/Invalid transition/);});This is integration: the StoreProvider sets up the validator, the executor handles the machine/* action, the state mutation flows through applyAction. Worth one or two tests per machine; deeper invariant + side-effect testing is faster at the unit layer with StateMachineValidator directly.
Action bindings
Section titled “Action bindings”Bindings are wired through the StoreProvider; useBoundActions reads context. Test them via the same wrapper.
import { defineBindings, useBoundActions } from '@input-actions/core';
const bindings = defineBindings({ counter: { onIncrement: [['action/increment', ['count']]] },});
test('useBoundActions returns the registered handlers', () => { const store = createSimpleStore({ count: 0 }); const { result } = renderHook( () => ({ handlers: useBoundActions('counter'), state: useStore<{ count: number }>(), }), { wrapper: ({ children }: { children: React.ReactNode }) => ( <StoreProvider store={store} bindings={bindings}> {children} </StoreProvider> ), }, );
act(() => result.current.handlers.onIncrement?.()); expect(result.current.state.count).toBe(1);});For machine-rooted bindings, dispatch a transition and verify the handler set changes shape:
test('machine-rooted handlers vary by mode', () => { const bindings = defineBindings({ 'wizard.controls': { machine: 'wizard', modes: { editing: { onSubmit: [['machine/transition', 'wizard', 'reviewing']] }, reviewing: { onConfirm: [['action/save', ['done'], true]] }, }, }, });
// ... set up store with wizard machine ... const { result } = renderHook(/* … */);
expect(Object.keys(result.current.handlers).sort()).toEqual(['onSubmit']); act(() => result.current.dispatch(['machine/transition', 'wizard', 'reviewing']), ); expect(Object.keys(result.current.handlers).sort()).toEqual(['onConfirm']);});The handler-set-changes-with-mode is the load-bearing assertion for machine-rooted bindings. Worth a test.
Debounce — fake timers
Section titled “Debounce — fake timers”For debounced async (action/async-debounce), use vitest’s fake timers.
import { afterEach, test, vi } from 'vitest';
afterEach(() => { vi.useRealTimers();});
test('debounce coalesces rapid dispatches', async () => { vi.useFakeTimers(); const handler = vi.fn().mockResolvedValue('ok'); const store = createSimpleStore({ _async: {} }); const { result } = renderHook(useStoreApi, { wrapper: makeWrapper(store, { search: handler }), });
act(() => { result.current.dispatch(['action/async-debounce', 'q', 'search', 100, 'a']); result.current.dispatch(['action/async-debounce', 'q', 'search', 100, 'b']); result.current.dispatch(['action/async-debounce', 'q', 'search', 100, 'c']); }); expect(handler).not.toHaveBeenCalled();
await act(async () => { await vi.advanceTimersByTimeAsync(150); }); expect(handler).toHaveBeenCalledTimes(1); expect(handler.mock.calls[0][0]).toBe('c');});advanceTimersByTimeAsync plays nicely with act. Resetting via vi.useRealTimers() in afterEach keeps cross-test contamination away.
Cancellation — the abort signal
Section titled “Cancellation — the abort signal”Test that the cancel strategy aborts the previous call:
test('cancel aborts in-flight signal and starts a new operation', async () => { const h = deferredHandler(); const store = createSimpleStore({ _async: {} }); const { result } = renderHook(useStoreApi, { wrapper: makeWrapper(store, { fetch: h.fn }), });
act(() => { result.current.dispatch(['action/async-cancel', 'op', 'fetch', 'a']); }); expect(h.signals[0].aborted).toBe(false);
act(() => { result.current.dispatch(['action/async-cancel', 'op', 'fetch', 'b']); }); expect(h.signals[0].aborted).toBe(true); expect(h.signals[1].aborted).toBe(false);});The signals array on deferredHandler lets the test inspect the AbortSignal each call received. Asserting on signal.aborted is the canonical check.
Component-level integration
Section titled “Component-level integration”When you do want to render a real component (not just a hook), the shape is the same — wrap with the provider and test through screen / fireEvent:
import { fireEvent, render, screen } from '@testing-library/react';import { useActions, useStore } from '@input-actions/core';
function Counter() { const count = useStore<{ count: number }, number>((s) => s.count); const actions = useActions(); return ( <button onClick={actions(['action/increment', ['count']])}> {count} </button> );}
test('clicking increments', () => { const store = createSimpleStore({ count: 0 }); render( <StoreProvider store={store}> <Counter /> </StoreProvider>, );
expect(screen.getByRole('button')).toHaveTextContent('0'); fireEvent.click(screen.getByRole('button')); expect(screen.getByRole('button')).toHaveTextContent('1');});Keep these tests few and focused on wiring. The logic of “increment increments” was already proven by the applyAction unit test on the previous page.
Common pitfalls
Section titled “Common pitfalls”| Issue | Fix |
|---|---|
State doesn’t update after dispatch | Wrap dispatch in act(() => …) — React batches updates within a tick. |
| State doesn’t update after a promise resolves | Wrap the resolution in await act(async () => …). |
| Tests interfere across files | afterEach(() => vi.useRealTimers()) — fake timers persist otherwise. |
Test mounts but useStore throws “must be used within a StoreProvider” | The wrapper option on renderHook is required; provider must wrap. |
| Async strategy tests flake | Use deferredHandler (control promise resolution explicitly) rather than setTimeout-based handlers. |
Where to go next
Section titled “Where to go next”- Unit testing recipes — the broader set of tests that don’t need rendering.
- Action types reference — every action variant you might dispatch in a test.
- The library’s own test suite is the canonical reference for these patterns.