Sub topic 12
Testing the paths through a flow
A guided flow has a small number of rules: which step is current, whether it is valid, and where Back goes. Those rules produce many possible journeys. This chapter shows how to test the rules and the journeys without opening a browser.
This chapter assumes you have read the earlier chapters on flow state, navigation, validation, and branching. It also assumes you know TypeScript and have used a test runner such as Node's built-in node:test, Jest, or Vitest. The examples reuse steps, advance, back, and progressLabel from earlier chapters. Put them in a file named flow.ts that exports them, along with the Data, Step, and FlowState types.
Why flows are easy to test when the logic is data
Earlier chapters put validation and branching in step definitions and put navigation in two pure functions. A pure function returns the same output for the same input and changes nothing outside itself. So you can test almost the whole flow by calling functions and comparing the results. You don't need a rendered screen.
Split your tests into four layers. Most of your tests belong in the lower layers, because they run fast and fail with a clear cause.
| Layer | What it checks | Example |
|---|---|---|
| Step | One step's `validate` and `next` | A bad email returns one error |
| Transition | One call to `advance` or `back` | A blocked advance keeps the user on the step |
| Path | A whole journey from start to finish | A business account visits `company` |
| Interface | Focus, announcements, and rendering | Errors are read aloud by a screen reader |
Setting up a test file
The file below uses node:test. Run it with npx tsx --test flow.test.ts, or use node --test on a Node version that can run TypeScript directly. If you use Jest or Vitest, the assertions translate one to one.
import { test } from "node:test";
import assert from "node:assert/strict";
import { steps, advance, back, progressLabel } from "./flow";
import type { Data, FlowState } from "./flow";
function start(data: Data = {}): FlowState {
return { current: "account", history: [], data, errors: [] };
}
const personal: Data = { email: "[email protected]", accountType: "personal" };
const business: Data = {
email: "[email protected]",
accountType: "business",
company: "Acme",
};Build state objects with a helper like start. If tests write out the full state by hand, every change to the state shape forces edits across the whole file. With the helper, you fix it in one place.
Testing steps in isolation
Step tests are the cheapest and should be the most numerous. Test each rule of validate, and test each outcome of next.
test("account: rejects an address without a domain", () => {
const errors = steps.account.validate({ email: "ana@" });
assert.deepEqual(errors, ["Enter a valid email address."]);
});
test("account: accepts a well-formed address", () => {
assert.deepEqual(steps.account.validate(personal), []);
});
test("account: business accounts go to company", () => {
assert.equal(steps.account.next(business), "company");
});
test("account: other accounts go to review", () => {
assert.equal(steps.account.next(personal), "review");
});
test("company: blank names are rejected", () => {
assert.equal(steps.company.validate({ company: " " }).length, 1);
});Check the exact error text in at least one test per rule. Users read that text, so a change to it should be a deliberate edit. Include boundary inputs: an empty string, a missing key, and whitespace only. The company rule uses trim(), so the whitespace case checks that it works.
Testing transitions
A transition test calls advance or back once and examines the new state. Three properties matter for advance:
- A failed validation leaves
currentandhistoryunchanged and fillserrors. - A successful advance moves to the id returned by
nextand pushes the old step ontohistory. - Advancing from the last step does not move and does not fabricate a history entry.
test("advance is blocked by validation", () => {
const before = start({ email: "nope" });
const after = advance(before, steps);
assert.equal(after.current, "account");
assert.deepEqual(after.history, []);
assert.equal(after.errors.length, 1);
});
test("advance records where the user came from", () => {
const after = advance(start(business), steps);
assert.equal(after.current, "company");
assert.deepEqual(after.history, ["account"]);
assert.deepEqual(after.errors, []);
});
test("back at the first step does nothing", () => {
const before = start(personal);
assert.deepEqual(back(before), before);
});
test("back undoes advance", () => {
const before = start(business);
assert.deepEqual(back(advance(before, steps)), before);
});The last test is a round-trip property: going forward and then back should restore the state exactly. Round-trip tests catch a whole class of bugs, such as a Back that forgets to pop the history or an advance that mutates data. You can write the same test for any pair of operations that should cancel out.
Testing whole paths
A path test starts at the first step, advances with valid data until the flow stops, and compares the list of visited step ids with the expected list. The helper below does this walk.
function walk(data: Data): string[] {
let state = start(data);
const visited = [state.current];
for (let i = 0; i < 20; i++) {
const next = advance(state, steps);
if (next.current === state.current) return visited;
state = next;
visited.push(state.current);
}
throw new Error("Flow did not finish within 20 steps");
}
const paths = [
{ name: "personal", data: personal, expected: ["account", "review"] },
{ name: "business", data: business, expected: ["account", "company", "review"] },
];
for (const p of paths) {
test("path: " + p.name, () => {
assert.deepEqual(walk(p.data), p.expected);
});
}The step limit of 20 turns an infinite loop into a failing test. A branch that points back at an earlier step would otherwise hang the test run.
The walker has a limit. It stops both when the user is blocked and when the flow is finished, because in both cases current does not change. A blocked path ends early, and the comparison with expected catches it. If you need to tell the two cases apart, return errors from the walker as well.
Covering branches without testing every combination
The number of combinations grows quickly. A flow with five independent yes/no branches has 32 combinations, and most of them add nothing. Cover branches with these rules instead:
- Write one path test for each outcome of each
nextfunction. This gives you every edge in the flow graph. - Add combination tests only where two branches interact. For example, add one if a later step's branch reads an answer that an earlier branch can skip.
- Add a test for every bug you fix. A regression test for a real failure is worth more than a guessed combination.
You can also check the graph itself. The test below confirms that no next function returns an id that is missing from steps, and that each step's key matches its id.
test("every next() points at a real step", () => {
for (const p of paths) {
for (const step of Object.values(steps)) {
const id = step.next(p.data);
assert.ok(id === null || id in steps, step.id + " points at " + id);
}
}
});
test("step ids match their keys", () => {
for (const [key, step] of Object.entries(steps)) {
assert.equal(step.id, key);
}
});This check matters because the compiler can't help here. Step ids are plain strings, so a typo such as "compnay" compiles and fails only when a user reaches it.
Edge cases that break flows
Most flow bugs appear when a user changes an earlier answer. Test these cases on purpose.
Changing an answer after going back
A user chooses a business account, reaches company, goes back, and switches to personal. The history must show the real route, and the remaining path must follow the new answer.
test("switching branch after Back follows the new answer", () => {
const onCompany = advance(start(business), steps);
const backAtAccount = back(onCompany);
const switched: FlowState = {
...backAtAccount,
data: { ...backAtAccount.data, accountType: "personal" },
};
const result = advance(switched, steps);
assert.equal(result.current, "review");
assert.deepEqual(result.history, ["account"]);
});This test also exposes a design question. The company answer is still in data, though the user is no longer on a path that asks for it. The model from earlier chapters keeps it. If you submit all of data, a personal account is sent with a company name. Decide what you want, then pin it with a test. One choice is to filter the submitted payload to the steps in history plus the current one. The other is to clear answers when a branch changes. Either way, a test should fail if the behavior changes by accident.
Stale history
History is a record of the route taken, not a list of all possible steps. Check that history never contains the current step and never contains duplicates. Both would mean a branch looped or Back popped the wrong entry.
test("history never contains the current step", () => {
let state = start(business);
for (let i = 0; i < 3; i++) {
state = advance(state, steps);
assert.ok(!state.history.includes(state.current));
}
});Progress labels
The label comes from history.length, so it must agree with Back as well as with forward movement.
test("progress follows navigation in both directions", () => {
const first = start(personal);
const second = advance(first, steps);
assert.equal(progressLabel(first), "Step 1");
assert.equal(progressLabel(second), "Step 2");
assert.equal(progressLabel(back(second)), "Step 1");
});Other cases to list
- Whitespace-only and very long input in every field.
- A valid answer that becomes invalid after the user edits it, then presses Next again.
- Double submission on the final step. Test that a second call cannot send the data twice.
- A saved draft that names a step you have since renamed or removed. Resuming should fall back to a safe step, and a test should force that case.
Property-style checks
Hand-written examples cover the cases you thought of. A property-based library such as fast-check generates many random inputs and checks that a rule always holds. Good rules for a flow include these:
- For any generated data,
walkfinishes within the step limit. - For any state reached by advancing,
backfollowed byadvancewith the same data returns to that step. - For any data, every step on the walked path has an entry in
steps.
Use these as a supplement. When one fails, the library shrinks the input to a small example. Copy that example into a normal test so the failure stays covered.
What to test through the interface
Pure-function tests can't tell you whether focus moves to the new step or whether a screen reader announces an error. Keep a small set of interface tests for those behaviors:
- After Next, focus lands on the new step's heading or first field.
- After a failed Next, the error summary is visible, has focus or is announced, and links to the field.
- Back restores the values the user typed.
Write only a few interface tests, because they are slow and tied to markup. Run them through one path that includes a failure and one that includes Back. The logic tests above carry the rest of the load.
A checklist for a new flow
- One test per validation rule, including boundary inputs.
- One test per
nextoutcome. - One path test per branch outcome, using the
walkhelper. - The graph checks: valid ids, matching keys, no cycle within the step limit.
- The Back round trip, plus a branch change after Back.
- A decision and a test for answers left behind on skipped steps.
- A few interface tests for focus, error announcement, and restored values.
Exercise
A new step billing is added. The account step now routes business accounts with plan equal to "paid" to billing, then to company; all other business accounts go straight to company. Which tests do you add or change, and what would catch a typo such as next: () => "compnay" in billing?
Show answer
Change the account next tests to cover three outcomes: personal goes to review, business with a free plan goes to company, and business with a paid plan goes to billing. Add step tests for any billing validation rule. Add a path test for the paid route that expects ["account", "billing", "company", "review"], and keep the free route test. The graph check "every next() points at a real step" catches the typo, as long as one of its fixtures reaches billing, so add the paid business data to the paths list. Also add a Back test from company on the paid route, which should return to billing and not to account.
Exercise
Why does the walk helper need an iteration limit, and what does a test that passes only because the walker stopped early look like?
Show answer
A bad branch could send the user back to an earlier step, so advance would never reach the end and the test would hang. The limit turns that into a failing test with a clear message. A walker also stops when validation blocks it, because current does not change. If the fixture data is invalid, the walker returns a short path such as ["account"]. The test fails only if the expected list is longer, so always compare against the full expected list and not just the last step.