Sub topic 14
Testing the Flow and Measuring Drop-Off
This chapter assumes you have read the earlier chapters on field state, validation, the step state machine, persistence, and accessibility. You should be comfortable with TypeScript and with basic unit testing in a tool such as Vitest or Jest. The goal is to check that a multi-step form works, then find out where real users give up on it.
Testing answers "does the flow behave as designed?" Measuring answers "does the design work for people?" You need both. A flow can pass every test and still lose half its users on step two.
What to Test, and at Which Level
A multi-step form has several kinds of logic, and each belongs at a different level of testing.
| Level | What it checks | Speed | Example |
|---|---|---|---|
| Unit | Pure functions: validators, reducer, visibility rules | Milliseconds | `validate("account", {})` returns an email error |
| Component | One step rendered with real DOM, keyboard input, and labels | Fast | Typing an invalid email and tabbing away shows the error |
| End to end | The whole flow in a real browser, including reload and submission | Slow | Fill all steps, reload mid-way, resume, submit |
| Accessibility | Roles, names, focus, and announcements | Fast to medium | Error summary receives focus after a failed step |
Put as much logic as you can at the unit level. This is the main payoff of the state machine design from earlier chapters: the reducer is a pure function, so you can test every transition without a browser.
Unit Testing the Reducer
The reducer from the state machine chapter has three rules worth locking down. Forward movement is blocked by validation errors. Backward movement keeps entered values. The step index never leaves the valid range.
import { describe, it, expect } from "vitest";
const steps = ["account", "details", "review"] as const;
type StepId = (typeof steps)[number];
type State = {
step: StepId;
values: Record<string, string>;
errors: Record<string, string>;
};
type Action =
| { type: "change"; name: string; value: string }
| { type: "next" }
| { type: "back" };
function validate(step: StepId, values: Record<string, string>): Record<string, string> {
const errors: Record<string, string> = {};
if (step === "account" && !values.email?.includes("@")) {
errors.email = "Enter an email address in the format [email protected].";
}
if (step === "details" && !values.name?.trim()) {
errors.name = "Enter your full name.";
}
return errors;
}
function reducer(state: State, action: Action): State {
const index = steps.indexOf(state.step);
switch (action.type) {
case "change":
return { ...state, values: { ...state.values, [action.name]: action.value } };
case "next": {
const errors = validate(state.step, state.values);
if (Object.keys(errors).length > 0) return { ...state, errors };
return { ...state, errors: {}, step: steps[Math.min(index + 1, steps.length - 1)] };
}
case "back":
return { ...state, errors: {}, step: steps[Math.max(index - 1, 0)] };
}
}
const start: State = { step: "account", values: {}, errors: {} };
describe("signup reducer", () => {
it("blocks next when the current step is invalid", () => {
const next = reducer(start, { type: "next" });
expect(next.step).toBe("account");
expect(next.errors.email).toBeDefined();
});
it("advances and clears errors when the step is valid", () => {
const filled = reducer(start, { type: "change", name: "email", value: "[email protected]" });
const next = reducer(filled, { type: "next" });
expect(next.step).toBe("details");
expect(next.errors).toEqual({});
});
it("keeps values when going back", () => {
const filled = reducer(start, { type: "change", name: "email", value: "[email protected]" });
const onDetails = reducer(filled, { type: "next" });
const back = reducer(onDetails, { type: "back" });
expect(back.step).toBe("account");
expect(back.values.email).toBe("[email protected]");
});
it("does not go before the first step", () => {
expect(reducer(start, { type: "back" }).step).toBe("account");
});
});Notice what the tests do not need: no DOM, no timers, no network. If a rule is hard to test this way, it is probably living in the wrong place, such as inside a component's event handler.
Test the Edge Cases That Hurt Users
Beyond the happy path, add tests for the cases that cause real data loss:
- Whitespace-only input in a required field (
" "must fail the name check). - Going back and forward repeatedly without losing values.
- A corrupted or missing saved draft, which must fall back to a fresh start.
- A conditional field that is hidden after the user filled it in. Its value must not appear in the submitted payload.
The last case is easy to check with the activeValues function from the conditional fields chapter:
import { it, expect } from "vitest";
type Values = Record<string, string>;
type Field = { name: string; visibleWhen?: (values: Values) => boolean };
const fields: Field[] = [
{ name: "delivery" },
{ name: "address", visibleWhen: (v) => v.delivery === "ship" },
];
function activeValues(values: Values): Values {
const result: Values = {};
for (const field of fields) {
if (!field.visibleWhen || field.visibleWhen(values)) {
if (field.name in values) result[field.name] = values[field.name];
}
}
return result;
}
it("drops answers from a hidden branch", () => {
const values = { delivery: "pickup", address: "1 Old Street" };
expect(activeValues(values)).toEqual({ delivery: "pickup" });
});Testing Persistence
Draft saving touches browser storage, so test it with a small in-memory stand-in. The key behavior is the failure path: bad stored data must not break the form.
import { it, expect, beforeEach } from "vitest";
const store = new Map<string, string>();
const sessionStorageStub = {
getItem: (key: string) => store.get(key) ?? null,
setItem: (key: string, value: string) => void store.set(key, value),
};
const DRAFT_KEY = "signup-draft";
function saveDraft(step: string, values: Record<string, string>): void {
sessionStorageStub.setItem(DRAFT_KEY, JSON.stringify({ step, values }));
}
function loadDraft(): { step: string; values: Record<string, string> } | null {
const raw = sessionStorageStub.getItem(DRAFT_KEY);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
}
beforeEach(() => store.clear());
it("restores what was saved", () => {
saveDraft("details", { email: "[email protected]" });
expect(loadDraft()).toEqual({ step: "details", values: { email: "[email protected]" } });
});
it("returns null for corrupted data instead of throwing", () => {
store.set(DRAFT_KEY, "{not json");
expect(loadDraft()).toBeNull();
});One gap remains. JSON.parse succeeding does not prove the data has the right shape. A draft saved by an older version of your form might name a step that no longer exists. Add a test that loads such a draft and confirm your app validates the step name before using it.
Component and Accessibility Tests
Component tests render one step and interact with it the way a user would. Query by label text or role, not by CSS class. If a query by label fails, a screen reader user has the same problem, so the test doubles as an accessibility check.
Check these behaviors:
- Every input is reachable with
getByLabelText. - After a failed "Next", focus moves to the error summary or the first invalid field.
- The invalid input has
aria-invalid="true"and anaria-describedbythat points at an element that exists. - After a successful step change, focus lands on the new step's heading.
Automated tools such as axe catch missing labels and invalid ARIA references, but they cannot judge whether focus order makes sense or whether an error message is helpful.
End-to-End Tests
Write a small number of browser tests for behavior that only a real browser can show. Good candidates are:
- The happy path from first step to the confirmation page.
- Reload on step two, then resume with values intact.
- The browser back button while on step two.
- A submission that fails on the server, followed by a retry that succeeds without retyping.
- A double-click on Submit that results in one request.
Mock the network at the browser level so you can force a failure on demand. Keep these tests few, because they are slow and the most likely to become flaky. Never rely on fixed waits. Wait for a visible condition, such as the step heading appearing.
Measuring Drop-Off
Tests tell you the flow works. They do not tell you why people leave. For that you need events that record movement through the flow.
Define the Events
Send a small, consistent set of events. Each carries the step ID and a session identifier that is not tied to a person's identity.
| Event | When it fires | What it tells you |
|---|---|---|
| `flow_started` | First step is shown | Size of the audience |
| `step_viewed` | A step is shown | How far people get |
| `step_completed` | Next succeeds | Progress |
| `validation_failed` | Next is blocked, with field names | Which fields cause trouble |
| `submit_attempted` | Submit is pressed | Intent to finish |
| `submit_failed` | The server rejects the request | Technical failures |
| `flow_completed` | Confirmation is shown | Success |
type FlowEvent = {
name:
| "flow_started"
| "step_viewed"
| "step_completed"
| "validation_failed"
| "submit_attempted"
| "submit_failed"
| "flow_completed";
step?: string;
fields?: string[];
sessionId: string;
at: number;
};
function track(event: Omit<FlowEvent, "at">): void {
const payload = JSON.stringify({ ...event, at: Date.now() });
navigator.sendBeacon("/analytics/flow", payload);
}navigator.sendBeacon queues a request that the browser delivers even if the user closes the tab. Use it instead of fetch for events fired as the page unloads.
Log field names, never field values. An event that contains an email address or a name turns your analytics store into a place holding personal data, with all the obligations that brings.
Read the Funnel
A funnel counts how many sessions reach each step. Divide each count by the previous one to get the step-to-step conversion rate.
| Step | Sessions | Conversion from previous |
|---|---|---|
| account | 1000 | n/a |
| details | 820 | 82% |
| review | 610 | 74% |
| confirmation | 580 | 95% |
In this example the largest loss is between details and review, so that step is where to look first. Start with the largest drop, but compare it to what you would expect. A step that asks for a payment card will lose more people than one asking for a name, and that is not a defect.
Find the Cause
A drop tells you where, not why. Combine the funnel with other signals:
validation_failedcounts by field. A field that fails often has a confusing rule or a bad error message.- Time spent on a step. Long times suggest users are hunting for information, such as a number they do not have to hand.
- Drop-off by device, browser, and assistive technology where you can measure it. A drop on one browser usually points to a bug.
submit_failedrates. If the last step loses people, check the server errors before blaming the design.
Then confirm with a change. Alter one thing, such as the wording of an error or the order of two fields, and compare the funnel before and after. Run it as an A/B test if you have enough traffic. With a few hundred sessions, small differences are noise, so do not act on a two-point swing.
Common Mistakes
- Testing only the happy path, so the first failed validation is also the first time the error code runs.
- Using fixed sleeps in end-to-end tests, which produces flaky results.
- Tracking too many events with unclear names, which makes the funnel hard to read.
- Logging entered values in analytics.
- Reading a drop-off as proof of a design flaw without checking for technical failures first.
Exercise
Your funnel shows 900 sessions at step one, 700 at step two, and 350 at step three. Step three asks for a phone number. validation_failed events on step three list the field "phone" in most cases. Which step has the largest drop, and what is your first hypothesis and the first thing you would check?
Show answer
Step three has the largest drop: 700 to 350 is 50% conversion, against about 78% for step one to two. The repeated validation_failed events on "phone" suggest the phone rule is rejecting valid input, for example by accepting only one number format or no spaces or country codes. First look at the validation rule and the error message wording with real examples of entered formats (only the format shape, not stored values), and check whether the field is required when it need not be. Then change the rule or message and compare the funnel.
Exercise
Write one unit test, in words, that would catch a data leak from a conditional field. What does it set up and what does it assert?
Show answer
Set up values where the user first chose "ship" and entered an address, then switched the delivery choice to "pickup", leaving the address value in state. Run the function that builds the submitted payload. Assert that the result contains the delivery field and does not contain the address field.