Sub topic 12
Reviewing and testing every state
This chapter assumes you have read the earlier chapters on the screen state model, loading patterns, empty and error states, accessibility, and modeling states in code. You should also be able to read basic HTML and TypeScript. Here you turn those ideas into a review routine and a test suite, so that every state of a screen is checked before release.
Why states need their own review
Most design reviews look at one screen: the happy path with realistic data. The loading, empty, and error states are usually built last, reviewed least, and broken first in production. A reviewer who sees only the success state cannot tell whether the other states exist.
A state review has two goals:
- Confirm that every state the screen can reach has been designed, built, and checked.
- Confirm that the transitions between states behave as intended, including timing and focus.
The checks are cheap compared with the cost of shipping a blank screen, a spinner that never ends, or an error that says only "Something went wrong."
Build a state inventory
Start from a state inventory. This is a table that lists each state the screen can be in, how a tester can force it, and what the user should see and be able to do. You can derive it directly from the type you wrote when modeling states in code.
| State | How to trigger it | What the user sees | What the user can do |
|---|---|---|---|
| Loading (fast) | Respond in under the spinner delay | Nothing extra, then content | Wait briefly |
| Loading (slow) | Delay the response by several seconds | Skeleton or spinner, status text | Wait, or cancel if offered |
| Empty (first use) | Return an empty list for a new account | Explanation and a create action | Create the first item |
| Empty (no results) | Search for text that matches nothing | Message naming the query, clear-filters action | Change or clear the search |
| Error (retryable) | Return a network failure or a 503 | Plain message, retry button | Retry |
| Error (not retryable) | Return a 403 or 404 | Message explaining the cause | Go back, request access, or contact support |
| Partial failure | Fail one of several requests | Content that loaded, plus a notice for the part that did not | Retry only the failed part |
| Success | Return normal data | The list or details | Use the screen |
Add a row for any state specific to your screen, such as "offline" or "stale data shown while refreshing." If you cannot say how to trigger a state, you cannot test it, and that is a finding in itself.
Every arrow in this diagram is a transition worth checking. Reviewers often verify the states but skip the arrows, and the arrows are where flicker, lost focus, and stale messages appear.
A design review checklist
Use the checklist below in a design review, working through one state at a time. Each question has a clear yes or no answer.
Loading
- Is there a visible response to the user's action within about 100 ms?
- Is the loading pattern appropriate to the wait: nothing, spinner, skeleton, progress bar, or optimistic update?
- Does the loading layout match the final layout closely enough to avoid a jump when content arrives?
- Is there a rule for what happens if loading takes much longer than expected, such as a message or a way out?
Empty
- Does the empty state say why the screen is empty: first use, no results, cleared, or no permission?
- Does it offer one clear next action that fits that cause?
- Is the empty state different from the loading state, so the user never mistakes one for the other?
Error
- Does the message say what happened in plain words, without codes or blame?
- Does it give a way forward: retry, edit, go back, or contact support?
- Is the user's work preserved, such as form input or a draft?
- Does the message sit near the thing that failed?
Cross-cutting
- Is every state announced to assistive technology in a suitable way?
- Does focus end up somewhere sensible after each transition?
- Do all states work at narrow widths, with large text, and in the dark theme?
- Is the copy reviewed for tone and consistency across the three kinds of state?
Make the states reachable
You cannot review what you cannot see. Give the team a way to put the screen into each state on demand. Three approaches work well, and teams often combine them.
- Component stories. Render the screen's view component with a fixed state object for each row of the inventory. Designers and reviewers can open every state without a backend.
- Mock responses. Intercept network calls in development and tests, and return a delay, an empty list, or an error on request.
- Debug switches. Add a query parameter or a development-only menu that forces a state, for example
?state=error. Keep these out of production builds.
Because the state is a discriminated union, a story is just a value of that type. The next section builds on the AsyncState type from earlier in the tutorial.
Automated tests for each state
Automated tests protect states from regressions. Separate them into three levels.
- Unit tests on the pure function that turns state into output. These are fast and cover every branch.
- Component tests that render the real component with each state and check text, roles, and focus.
- End-to-end tests that run against a real or mocked server and check the transitions, including timing.
Unit-testing every branch
The renderList function from the modeling chapter is a pure function of its input. That makes it simple to test exhaustively. The following example uses Node's built-in test runner, so it needs no extra packages. Save it as render-list.test.ts and run it with a TypeScript-capable Node setup, such as node --test with a loader or tsx --test.
import { test } from "node:test";
import assert from "node:assert/strict";
type AsyncState<T> =
| { status: "loading" }
| { status: "error"; message: string; retryable: boolean }
| { status: "success"; data: T };
function renderList(state: AsyncState<string[]>): string {
switch (state.status) {
case "loading":
return "Loading projects…";
case "error":
return state.retryable
? `${state.message} Try again.`
: state.message;
case "success":
return state.data.length === 0
? "No projects yet. Create your first project."
: state.data.join(", ");
}
}
test("loading state shows a loading message", () => {
assert.equal(renderList({ status: "loading" }), "Loading projects…");
});
test("retryable error invites the user to try again", () => {
const text = renderList({
status: "error",
message: "We couldn't load your projects.",
retryable: true,
});
assert.equal(text, "We couldn't load your projects. Try again.");
});
test("non-retryable error does not suggest retrying", () => {
const text = renderList({
status: "error",
message: "You don't have access to these projects.",
retryable: false,
});
assert.ok(!text.includes("Try again"));
});
test("success with no items shows the empty state", () => {
const text = renderList({ status: "success", data: [] });
assert.equal(text, "No projects yet. Create your first project.");
});
test("success with items lists them", () => {
const text = renderList({ status: "success", data: ["Alpha", "Beta"] });
assert.equal(text, "Alpha, Beta");
});Notice that the empty case is a test of the success branch with zero items. That matches the design: empty is a distinct case of successful data, not a failure. A test that mixes the two would hide a bug where an empty response is treated as an error.
Testing the spinner delay
The delayed spinner is timing logic, so it needs a test that controls time. Use fake timers rather than waiting for real milliseconds. The example below tests the showAfterDelay helper with Node's mock timers.
import { test, mock } from "node:test";
import assert from "node:assert/strict";
function showAfterDelay(delayMs: number, show: () => void): () => void {
const id = setTimeout(show, delayMs);
return () => clearTimeout(id);
}
test("spinner appears when the request is slow", () => {
mock.timers.enable({ apis: ["setTimeout"] });
const show = mock.fn();
showAfterDelay(300, show);
mock.timers.tick(299);
assert.equal(show.mock.callCount(), 0);
mock.timers.tick(1);
assert.equal(show.mock.callCount(), 1);
mock.timers.reset();
});
test("spinner never appears when the request is fast", () => {
mock.timers.enable({ apis: ["setTimeout"] });
const show = mock.fn();
const cancel = showAfterDelay(300, show);
mock.timers.tick(100);
cancel();
mock.timers.tick(1000);
assert.equal(show.mock.callCount(), 0);
mock.timers.reset();
});The first test checks the boundary: nothing at 299 ms, the spinner at 300 ms. The second test checks the case the delay exists for, a fast response that cancels the spinner. Boundary tests like these catch off-by-one mistakes and forgotten cancellations.
Checking accessibility in component tests
Component tests can assert that state changes are exposed correctly. Query by role, because roles are what assistive technology uses. In a typical Testing Library setup, you would check things like these:
- The loading region has
role="status", or the busy list hasaria-busy="true". - The error message has
role="alert". - After a failed submit, focus moves to the error summary or the first invalid field.
- After a successful retry, the error message is removed from the page, not merely hidden with a style that leaves it in the accessibility tree.
A role-based query fails if the markup is wrong, so the test doubles as a check that the announcement works. Automated tests cannot prove the announcement sounds right, though. That needs a manual pass.
Testing transitions and timing
Transitions are where bugs hide, so give them explicit cases.
- Retry after error. Force an error, click retry, and confirm the error clears, loading appears, and content replaces it. Check that the old error does not flash back.
- Fast then slow. Confirm that a 50 ms response shows no spinner, and a 2 s response shows one that stays visible for a minimum time, so it does not blink.
- Refresh with existing content. Confirm that content stays visible while new data loads, unless the design says otherwise.
- Overlapping requests. Trigger two requests in quick succession, such as typing in a search box, and confirm that the older response cannot overwrite the newer one.
- Leaving mid-request. Navigate away while loading and confirm no error or state update happens on the departed screen.
Overlapping requests deserve special attention. A slow first response arriving after a fast second one is a classic cause of a screen that shows results for the wrong query, with no error to warn anyone.
Manual exploratory pass
After automation, do a short manual pass. Use browser developer tools to simulate conditions that tests rarely cover:
- Throttle the network to a slow profile and watch the loading experience.
- Switch the network off and perform an action, to see the offline error.
- Block one request in the network panel to produce a partial failure.
- Enlarge the text and zoom to 200% and check that messages are not clipped.
- Navigate using only the keyboard through retry and recovery actions.
- Turn on a screen reader and walk through a load, an empty result, and an error.
Record what you find against the state inventory, so the next reviewer sees which rows have been checked and how.
Common mistakes
- Only testing success. Unit tests cover the happy path while error and empty branches have no tests at all.
- Treating empty as an error in tests. A test that expects an error for an empty list encodes the wrong design.
- Real timers in tests. Waiting for real delays makes tests slow and flaky. Use fake timers.
- Skipping the arrows. States are checked in isolation, but the transitions between them are not.
- Debug switches left on. A state-forcing parameter that reaches production lets users see broken screens.
- No owner. Nobody is responsible for the inventory, so it goes stale as the screen changes. Assign it to whoever owns the screen, and update it in the same change that adds a state.
Release gate
Before release, confirm each of these:
- The state inventory lists every reachable state, and each row has a way to trigger it.
- Every row has an automated test or a recorded manual check.
- The checklist above has been completed for the new or changed states.
- A screen reader pass has been done on loading, empty, and error states.
- Copy for all non-success states has been reviewed by someone other than its author.
Exercise
A search screen can show results, an empty result for a query, a retryable network error, and a loading state. List the tests you would write to cover its transitions and timing, and name one bug that only a transition test would catch.
Show answer
Write tests for these cases. First, a loading state that appears only after the spinner delay, using fake timers with a boundary check just below and at the delay. Second, a fast response that cancels the spinner so it never shows. Third, a zero-result response that shows the "no results" empty state with the query named and a clear-search action, not an error. Fourth, a network failure that shows a retryable error with a retry button, and a retry that clears the error, shows loading, and then shows results. Fifth, two overlapping searches where the slower, older response arrives last and must not replace the newer results. The overlapping-request test catches a bug that only appears across transitions: the screen shows results for an old query while the search box shows a new one, with no error. Single-state tests pass in this case, because each state looks correct in isolation.
Exercise
Why should the "success with an empty list" case be tested as part of the success branch rather than the error branch, and what bug does a separate test protect against?
Show answer
An empty list is valid data, not a failure, so the design treats it as a case of success with zero items and gives it its own message and next action. Testing it on the success branch keeps the test aligned with that design. It protects against the bug where code treats a falsy or empty response as an error, which would show an error message and a retry button for a user who simply has nothing yet. Retrying would never help, because the server answered correctly.