Skip to content

Checkpoint: Regression Suite

The Course
•
25 min study

The workspace holds Day 3's request reducer and an async refresh(load) that starts a request, awaits its loader and then dispatches finish. Write a test suite for it that uses all three of today's tools, each for the claim it can actually prove:

  • Two negative type tests (in a function that is never called): a ready state without a title must not compile, and a finish action without a request id must not compile.
  • Two controlled schedules with deferred promises: start an old and a newer refresh, then finish the old one first (the display must still say loading, then New), and in a fresh run finish the newer one first (New, and still New after the stale one finishes).
  • A mutation table: for each defect below, say which test catches it, then try it.
Defect to introduceWhich test should fail?
Drop state.request !== action.request from reduce?
Make request optional on the finish action?
Make title optional on the ready state?

Use an assertEqual(actual, expected, label) that names the failing case, and print the success line only after every check.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
let release: (value: string) => void = () => {};
const pending = new Promise<string>(resolve => {
  release = resolve;
});
let seen = "nothing yet";

const waiting = pending.then(value => {
  seen = value;
});

console.log(seen);
release("done");
await waiting;
console.log(seen);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
nothing yet
done

Acceptance cases before you code

Predict what each check observes before writing it.

Case to tryWhat your result should demonstrate
{ tag: "ready", request: 1 } assigned to StateA compile error, so the directive above it is used
Old finishes while the newer request is loadingDisplay still shows loading
Newer finishes, then oldDisplay shows New both times
Asserting before awaiting the refresh you just releasedThe continuation has not run yet, so the check sees stale state: always await first

Your turn

Exercise

Checkpoint: Regression Suite: practice

Write the suite described above under the provided code and print 4 schedule checks passed. Then fill in the mutation table by introducing each defect in turn.

Your workspaceTypeScript
type State =
  | { tag: "idle" }
  | { tag: "loading"; request: number }
  | { tag: "ready"; request: number; title: string };

type Action =
  | { type: "start"; request: number }
  | { type: "finish"; request: number; title: string };

function reduce(state: State, action: Action): State {
  if (action.type === "start") {
    return { tag: "loading", request: action.request };
  }
  if (state.tag !== "loading" || state.request !== action.request) {
    return state;
  }
  return { tag: "ready", request: action.request, title: action.title };
}

let state: State = { tag: "idle" };
let nextRequest = 0;

async function refresh(load: () => Promise<string>): Promise<void> {
  nextRequest += 1;
  const request = nextRequest;
  state = reduce(state, { type: "start", request });
  const title = await load();
  state = reduce(state, { type: "finish", request, title });
}

function deferred<T>() {
  let resolve: (value: T) => void = () => {};
  const promise = new Promise<T>(done => {
    resolve = done;
  });
  return { promise, resolve };
}

// Add: two negative type tests, assertEqual, and two controlled schedules.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Type tests and schedules prove different things. A negative type test proves a wrong program can't be written; a schedule proves the program that can be written behaves correctly in an order you chose.

Hint 2: a first step

For schedule A: create two deferreds, call refresh with each promise (old first), resolve the old one, await that refresh, then assert what is displayed.

Show one solution
One possible solutionTypeScript
type State =
  | { tag: "idle" }
  | { tag: "loading"; request: number }
  | { tag: "ready"; request: number; title: string };

type Action =
  | { type: "start"; request: number }
  | { type: "finish"; request: number; title: string };

function reduce(state: State, action: Action): State {
  if (action.type === "start") {
    return { tag: "loading", request: action.request };
  }
  if (state.tag !== "loading" || state.request !== action.request) {
    return state;
  }
  return { tag: "ready", request: action.request, title: action.title };
}

let state: State = { tag: "idle" };
let nextRequest = 0;

async function refresh(load: () => Promise<string>): Promise<void> {
  nextRequest += 1;
  const request = nextRequest;
  state = reduce(state, { type: "start", request });
  const title = await load();
  state = reduce(state, { type: "finish", request, title });
}

// Compile-time tests: checked by Check types, never called.
function typeTests(): void {
  // @ts-expect-error a ready state must carry its title
  const missingTitle: State = { tag: "ready", request: 1 };
  // @ts-expect-error a finish action must say which request it answers
  reduce(state, { type: "finish", title: "Old" });
}

function deferred<T>() {
  let resolve: (value: T) => void = () => {};
  const promise = new Promise<T>(done => {
    resolve = done;
  });
  return { promise, resolve };
}

function assertEqual<T>(actual: T, expected: T, label: string): void {
  if (actual !== expected) {
    throw new Error(`${label}: expected ${String(expected)}, got ${String(actual)}`);
  }
}

function shown(): string {
  return state.tag === "ready" ? state.title : state.tag;
}

// Schedule A: the old request finishes first, while the newer one is loading.
let old = deferred<string>();
let newer = deferred<string>();
let first = refresh(() => old.promise);
let second = refresh(() => newer.promise);
old.resolve("Old");
await first;
assertEqual(shown(), "loading", "old finished first");
newer.resolve("New");
await second;
assertEqual(shown(), "New", "newer finished last");

// Schedule B: the newer request finishes first.
state = { tag: "idle" };
old = deferred<string>();
newer = deferred<string>();
first = refresh(() => old.promise);
second = refresh(() => newer.promise);
newer.resolve("New");
await second;
assertEqual(shown(), "New", "newer finished first");
old.resolve("Old");
await first;
assertEqual(shown(), "New", "stale result ignored");

console.log("4 schedule checks passed");

Enable JavaScript to edit and type-check this example.

Text
4 schedule checks passed

The mutation table, verified:

DefectCaught by
Drop state.request !== action.requestSchedule A, at run time: old finished first: expected loading, got Old
Make finish's request optionalThe second type test: Check types reports TS2578, unused '@ts-expect-error' directive
Make ready's title optionalThe first type test (TS2578), plus a TS2322 in shown

The two type defects compile into perfectly working JavaScript, so no runtime test notices them; the directive is the only alarm. The ordering defect type-checks, so only a schedule notices it, and only the schedule where the old request finishes first. Schedule B guards a different promise: once the newer result is shown, nothing older may replace it.

Change it and test it

Add a third negative type test: a start action carrying a title must not compile. Then move one assertion above the await that precedes it and explain the result. Finally, explain why neither kind of test could replace the other for this reducer.

Was this article helpful?

Your response is saved on this device.