Skip to content

Testing the Public Contract

The Course
•
15 min study

The download has two test layers. contracts.ts contains four intentional invalid usages under @ts-expect-error and is included in normal compiler checking. catalogue.test.mjs runs the emitted JavaScript to verify normalization, issue paths, duplicate ids, state transitions and async dependency failures.

Locally, run npm test after npm install (setup is in the previous lesson, and is optional). Its build step checks the type contracts before running five grouped runtime cases. Do not execute the emitted contracts.js file; it contains deliberately invalid operations that only exist as compile checks.

Challenge both layers. Removing readonly from pages should make a negative directive unused and fail the compiler. Removing duplicate-id validation or the request-id comparison should still compile but fail runtime tests. Restore every mutation afterward.

The schedule group connects the actual createLoader and reduce exports. It allocates ids before awaiting, then releases old/new transports in both orders. Old success and old failure must leave the current loading or ready state unchanged. This checks orchestration as well as individual reducer transitions.

The test strategy is intentionally small: it checks this library's advertised behavior without snapshots of implementation internals. A new public feature needs corresponding evidence, not just more type aliases.

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
type Result<T> =
  | {
      ok: true;

      value: T;
    }
  | {
      ok: false;

      message: string;
    };

function read(result: Result<number>): number | null {
  return result.ok ? result.value : null;
}

if (read({ ok: true, value: 0 }) !== 0) {
  throw new Error("Zero lost");
}

if (read({ ok: false, message: "bad" }) !== null) {
  throw new Error("Failure lost");
}

console.log("2 runtime cases passed");

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
2 runtime cases passed

Connect direct transition tests to full request schedules

Decoder tests protect field truth; reducer tests protect transitions for already constructed actions. The schedule group connects real loaders and reducer calls so request ids survive actual awaiting. Keep these layers separate when interpreting coverage. A stale-result test after ready does not replace the case where a newer request is still loading.

Boundary or caseWhat to inspect
Positive normalized dataCheck projected output and unchanged source
Invalid field or duplicateReject with a specific path rather than partial success
Old and new completionCross both orders with old success and old failure

For each deliberate mutation, name its distinguishing assertion before changing source. Then weaken readonly and explain why the negative consumer should fail even when the same runtime fixtures still pass. Restore and rebuild between experiments.

Your turn

Exercise

Testing the Public Contract: practice

The project's second test group checks a cross-row rule: decodeCatalogue rejects a duplicate id, after normalization. Rebuild that rule and its test in the browser. The workspace has the Day 4 decoders. Write decodeCatalogue (arrayOf(decodeBook), then a Set of ids that reports the duplicate's row as index.id with message Duplicate id), and three assertEqual cases: unique ids give ok 2, ids "b1" and " b1 " give 1.id: Duplicate id, and a bad second row's pages is still reported first as 1.pages: Expected count. Print 3 catalogue cases passed, then disable the Set check and read which case fails.

Your workspaceTypeScript
type Issue = { path: string; message: string };
type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
type Decoder<T> = (value: unknown) => Result<T>;

function at(prefix: string, path: string): string {
  return path === "" ? prefix : `${prefix}.${path}`;
}

const count: Decoder<number> = value =>
  typeof value === "number" && Number.isInteger(value) && value >= 0
    ? { ok: true, value }
    : { ok: false, issue: { path: "", message: "Expected count" } };

function field<T>(name: string, decode: Decoder<T>): Decoder<T> {
  return value => {
    if (typeof value !== "object" || value === null) {
      return { ok: false, issue: { path: "", message: "Expected object" } };
    }
    const raw: unknown = Reflect.get(value, name);
    const result = decode(raw);
    if (result.ok) {
      return result;
    }
    return {
      ok: false,
      issue: { path: at(name, result.issue.path), message: result.issue.message }
    };
  };
}

const text: Decoder<string> = value =>
  typeof value === "string" && value.trim() !== ""
    ? { ok: true, value: value.trim() }
    : { ok: false, issue: { path: "", message: "Expected text" } };

type Book = {
  readonly id: string;
  readonly title: string;
  readonly pages: number;
};

function decodeBook(value: unknown): Result<Book> {
  const id = field("id", text)(value);
  if (!id.ok) {
    return id;
  }
  const title = field("title", text)(value);
  if (!title.ok) {
    return title;
  }
  const pages = field("pages", count)(value);
  if (!pages.ok) {
    return pages;
  }
  return {
    ok: true,
    value: { id: id.value, title: title.value, pages: pages.value }
  };
}

function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
  return value => {
    if (!Array.isArray(value)) {
      return { ok: false, issue: { path: "", message: "Expected array" } };
    }
    const output: T[] = [];
    for (const [index, element] of value.entries()) {
      const item: unknown = element;
      const result = decode(item);
      if (!result.ok) {
        return {
          ok: false,
          issue: {
            path: at(String(index), result.issue.path),
            message: result.issue.message
          }
        };
      }
      output.push(result.value);
    }
    return { ok: true, value: output };
  };
}

// Write decodeCatalogue, assertEqual, describe(result) and three cases here.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Uniqueness is a rule about the whole list, so it can only run after every row has decoded; by then decodeBook has already trimmed each id, which is what makes " b1 " a duplicate.

Hint 2: a first step

Return arrayOf's failure unchanged when the rows are invalid. Otherwise loop over result.value.entries() with a Set<string> of ids seen so far.

Show one solution
One possible solutionTypeScript
type Issue = { path: string; message: string };
type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
type Decoder<T> = (value: unknown) => Result<T>;

function at(prefix: string, path: string): string {
  return path === "" ? prefix : `${prefix}.${path}`;
}

const count: Decoder<number> = value =>
  typeof value === "number" && Number.isInteger(value) && value >= 0
    ? { ok: true, value }
    : { ok: false, issue: { path: "", message: "Expected count" } };

function field<T>(name: string, decode: Decoder<T>): Decoder<T> {
  return value => {
    if (typeof value !== "object" || value === null) {
      return { ok: false, issue: { path: "", message: "Expected object" } };
    }
    const raw: unknown = Reflect.get(value, name);
    const result = decode(raw);
    if (result.ok) {
      return result;
    }
    return {
      ok: false,
      issue: { path: at(name, result.issue.path), message: result.issue.message }
    };
  };
}

const text: Decoder<string> = value =>
  typeof value === "string" && value.trim() !== ""
    ? { ok: true, value: value.trim() }
    : { ok: false, issue: { path: "", message: "Expected text" } };

type Book = {
  readonly id: string;
  readonly title: string;
  readonly pages: number;
};

function decodeBook(value: unknown): Result<Book> {
  const id = field("id", text)(value);
  if (!id.ok) {
    return id;
  }
  const title = field("title", text)(value);
  if (!title.ok) {
    return title;
  }
  const pages = field("pages", count)(value);
  if (!pages.ok) {
    return pages;
  }
  return {
    ok: true,
    value: { id: id.value, title: title.value, pages: pages.value }
  };
}

function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
  return value => {
    if (!Array.isArray(value)) {
      return { ok: false, issue: { path: "", message: "Expected array" } };
    }
    const output: T[] = [];
    for (const [index, element] of value.entries()) {
      const item: unknown = element;
      const result = decode(item);
      if (!result.ok) {
        return {
          ok: false,
          issue: {
            path: at(String(index), result.issue.path),
            message: result.issue.message
          }
        };
      }
      output.push(result.value);
    }
    return { ok: true, value: output };
  };
}

const decodeCatalogue: Decoder<readonly Book[]> = value => {
  const result = arrayOf(decodeBook)(value);
  if (!result.ok) {
    return result;
  }
  const ids = new Set<string>();
  for (const [index, book] of result.value.entries()) {
    if (ids.has(book.id)) {
      return { ok: false, issue: { path: `${index}.id`, message: "Duplicate id" } };
    }
    ids.add(book.id);
  }
  return result;
};

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

function describe(result: Result<readonly Book[]>): string {
  return result.ok
    ? `ok ${result.value.length}`
    : `${result.issue.path}: ${result.issue.message}`;
}

const book = { id: "b1", title: "Types", pages: 120 };

assertEqual(describe(decodeCatalogue([book, { ...book, id: "b2" }])), "ok 2", "unique ids");
assertEqual(describe(decodeCatalogue([book, { ...book, id: " b1 " }])), "1.id: Duplicate id", "padded duplicate");
assertEqual(describe(decodeCatalogue([book, { ...book, pages: -1 }])), "1.pages: Expected count", "row rule runs first");
console.log("3 catalogue cases passed");

Enable JavaScript to edit and type-check this example.

Text
3 catalogue cases passed

The checker guarantees decodeCatalogue is a Decoder<readonly Book[]> and that result.value is read only after !result.ok has returned. Uniqueness is invisible to the types: with the Set check disabled, everything still compiles and the run stops at padded duplicate: expected 1.id: Duplicate id, got ok 2. The padded case is the important one, because a check on raw input ids would pass "b1" and " b1 " as different; the third case pins down that row rules run before the cross-row rule.

Change it and test it

Run all project cases before changing source. Then introduce each documented mutation and identify the layer that catches it. Explain why a type test may pass while data validation is wrong, and why runtime tests cannot prove a public signature rejects an invalid TypeScript caller.

Was this article helpful?

Your response is saved on this device.