Testing & Tooling: The Safety Harness

Testing & Tooling: The Safety Harness in TypeScript: A passenger lift is kept safe by two entirely different mechanisms, and neither could do the other's job.

The Analogy: The Passenger Lift's Door Interlock and Annual Load Test

A passenger lift is kept safe by two entirely different mechanisms, and neither could do the other's job. The first is the door interlock: an electrical and mechanical arrangement that makes it physically impossible for the car to move unless every landing door and the car gate is proven shut and locked. It works on every single trip, without anyone thinking about it, and it rules out a whole category of accident, moving with a door open, once and for all. The second is the annual load test, where an engineer places known test weights in the car and confirms that the lift actually raises its rated load, that the brake holds it, and that it stops level at each floor. A TypeScript project has exactly this pair: the type checker is the interlock, and the test suite is the load test.

The interlock's virtue is that it is continuous and free at the point of use. Once wired in, it is checked automatically every time the car is called, costs the operator nothing per trip, and cannot be forgotten. But notice what it does not do: it says nothing whatever about whether the lift raises the correct load or stops at the right floor. The type checker is the same. It runs over the whole codebase, catches an enormous class of mistakes, a misspelt field, a string passed where a number was wanted, a missing case, and it does so before the code ever runs. And it too is silent on behaviour: that total(items) returns a number is an interlock guarantee, but whether it returns the right number is entirely outside its remit.

The load test covers exactly the gap the interlock leaves. The engineer brings weights of a known mass, places them deliberately, and checks the actual, measured behaviour of the machine against what it is rated to do. That is what a test is: known inputs placed on purpose, and an assertion about the observed output. The two mechanisms are complementary rather than competing, because the interlock cannot weigh a load and the load test does not run on every trip. A project that leans on types to prove behaviour, or on tests to prove shape, has misunderstood which tool measures what, and the rule of thumb is simply that types check shape and tests check behaviour.

The failure mode is trusting one mechanism to cover the whole danger. A lift with a perfect interlock but no load test may glide with its doors safely locked straight past its rated capacity and part a cable; a lift load-tested once but with a defeated interlock can kill someone the very next trip when a door is forced. In code, "it compiled, so it works" trusts only the interlock and ships wrong arithmetic with confidence, while "the tests pass, so types do not matter" trusts only the load test and lets a refactor silently loosen a public API. There is a subtler trap too: a load test performed with the wrong test weights certifies nothing, exactly as a test whose expected value is itself mistaken will pass against broken code. Two honest, independent checks are the point, and each is only as good as the standard it is measured against.


Syntax or Core Structure

A test states known inputs and asserts the observed output. Stripped of any framework, that is a function that compares an actual value against an expected one and reports the verdict. The example below defines a real function, then runs three hand-written checks against it, each printing a deterministic pass or fail line.

// src/total.ts
interface Item {
    price: number;
    qty: number;
}

function total(items: Item[], taxPercent: number): number {
    const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
    return subtotal + Math.trunc((subtotal * taxPercent) / 100);
}

function check(name: string, actual: number, expected: number): string {
    return (actual === expected ? "pass " : "fail ") + name;
}

console.log(check("pair", total([{ price: 500, qty: 2 }, { price: 250, qty: 1 }], 0), 1250));
console.log(check("with tax", total([{ price: 1000, qty: 1 }], 10), 1100));
console.log(check("empty", total([], 0), 0));

Output:

pass pair
pass with tax
pass empty

Each check places a known cart and tax rate, computes the actual total, and compares it to the expected value. The first sums 500 * 2 + 250 * 1 = 1250 at zero tax, matching 1250. The second is 1000 plus Math.trunc(1000 * 10 / 100) = 100, giving 1100. The third totals an empty cart to 0. All three verdicts are pass, because the observed output equals the asserted expectation. The type checker had already guaranteed that total returns a number; these checks add the separate guarantee that it returns the correct number.


Technical Depth: Fixtures, Honest Mocks, and Who Catches What

Good tests lean on two typing patterns: a factory that builds fixtures from partial input, and a mock that is checked against the real interface. A clear division of labour between the tools then decides what each is responsible for.

A fixture factory from Partial input

Restating a full object in every test is noise and, worse, a maintenance trap: add a required field and every literal breaks. A factory taking Partial<T> lets each test state only the fields it cares about.

// src/factory.ts
interface CartItem {
    id: string;
    price: number;
    qty: number;
}

function item(over: Partial<CartItem>): CartItem {
    return { id: "x", price: 100, qty: 1, ...over };
}

const a = item({ price: 500, qty: 2 });
const b = item({ qty: 3 });

console.log(a.price * a.qty);
console.log(b.price * b.qty);
console.log(a.price * a.qty + b.price * b.qty);

Output:

1000
300
1300

The factory supplies sensible defaults and lets the spread override only what a test names. Item a overrides both price and quantity, giving 500 * 2 = 1000; item b overrides only quantity, keeping the default price of 100, giving 100 * 3 = 300; together they are 1300. Add a required field to CartItem and only item needs updating, not every test that ever built one.

A mock checked with satisfies

A mock that has drifted from the real interface is worse than no mock, because it passes while the production call site is broken. Using satisfies checks the mock against the contract while keeping its precise inferred type, so a recording array still type-checks.

// src/mock.ts
interface Gateway {
    charge: (amount: number) => number;
}

const calls: number[] = [];
const gateway = {
    charge: (amount: number) => {
        calls.push(amount);
        return amount;
    },
} satisfies Gateway;

function checkout(g: Gateway, amounts: number[]): number {
    let paid = 0;
    for (const amount of amounts) {
        paid += g.charge(amount);
    }
    return paid;
}

const total = checkout(gateway, [120, 80]);

console.log(calls.length);
console.log(calls.join(","));
console.log(total);

Output:

2
120,80
200

The satisfies Gateway check confirms the mock matches the interface without widening its type, so the calls recorder keeps working. checkout charges each amount in turn, so calls records 120 then 80, its length is 2, and the paid total is 120 + 80 = 200. Add a method to Gateway and this object stops compiling, which is the point: the mock cannot silently fall behind the real contract. Had this used as Gateway instead, a missing method would have been hidden.

Who catches what

The tools divide the work cleanly, and the table names which mechanism owns each concern.

ConcernOwned byWhat it proves
shape correctnessthe type checkerthe value has the right structure
behaviourthe test suitethe value is actually right
public API stabilitytype-level testsan exported generic still resolves
unhandled promisestype-aware linta promise is awaited or handled
formattingthe formatterstyle is consistent, not litigated

Reading down the owned-by column, shape belongs to the type checker and behaviour to tests, the two independent safety systems, while type-level tests guard an API you ship, lint catches a floating promise types alone miss, and formatting is a settled question rather than a review argument.


Real World Example: A Test Suite That Catches a Real Bug

A test suite is the load test applied to a function. This one runs several cases through total, each with a known cart, a known tax rate, and an expected result, and reports a pass or fail per case with a final count. One case carries a wrong expectation on purpose, standing in for a genuine behaviour bug that the type checker could never see, so the suite catches what the interlock misses.

// src/suite.ts
interface Item {
    price: number;
    qty: number;
}

function total(items: Item[], taxPercent: number): number {
    const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
    return subtotal + Math.trunc((subtotal * taxPercent) / 100);
}

interface Case {
    name: string;
    items: Item[];
    tax: number;
    expected: number;
}

function pad(text: string, width: number): string {
    const gap = width - text.length;
    return text + " ".repeat(gap > 0 ? gap : 0);
}

const cases: Case[] = [
    { name: "pair", items: [{ price: 500, qty: 2 }], tax: 0, expected: 1000 },
    { name: "tax", items: [{ price: 1000, qty: 1 }], tax: 10, expected: 1100 },
    { name: "empty", items: [], tax: 0, expected: 0 },
    { name: "trio", items: [{ price: 30, qty: 3 }], tax: 0, expected: 100 },
];

let passed = 0;
console.log("cases: " + cases.length);
console.log(pad("CASE", 8) + "RESULT");
for (const c of cases) {
    const actual = total(c.items, c.tax);
    const ok = actual === c.expected;
    if (ok) {
        passed++;
    }
    console.log(pad(c.name, 8) + (ok ? "pass" : "fail"));
}
console.log("passed: " + passed + "/" + cases.length);

Output:

cases: 4
CASE    RESULT
pair    pass
tax     pass
empty   pass
trio    fail
passed: 3/4

Trace each case. The pair totals 500 * 2 = 1000 at zero tax, matching its expectation, so it passes. The tax case is 1000 + Math.trunc(1000 * 10 / 100) = 1100, matching, so it passes. The empty cart totals 0, matching, so it passes. The trio computes 30 * 3 = 90, but its expected value is 100, so actual === expected is false and it reports fail; three of the four cases pass, giving passed: 3/4. That failing case is the whole point: it is a behaviour mismatch, a wrong number, that no type could ever have flagged because the shape was correct throughout.

The value of the suite is exactly that it measures behaviour the type checker is blind to. Every case here type-checks perfectly, total returns a number in all of them, yet the suite still surfaces a discrepancy between what the code computes and what was expected, which is the load test finding a fault the interlock cannot.

The design's honest limitation is the one the analogy warned about: the suite is only ever as good as its expected values. Here the trio expectation of 100 is the wrong weight, so the "failure" is really a fault in the test, not the code, and a suite can just as easily carry a wrong expectation that makes a broken function look correct, a false pass no amount of running will reveal. Two further gaps sit alongside: there are no type-level assertions here, so a refactor that loosened total's signature from number to number | undefined would pass every one of these behaviour cases while quietly weakening the public API; and the pass or fail verdict is a bare string, so a typo such as "pas" would silently be treated as a failure with no error, which a real assertion library removes by throwing rather than returning text.


Common Mistakes

  1. Believing a successful build means the types were checked. Many bundlers strip types without checking them, so a green build tells you nothing unless tsc --noEmit runs as its own step.
  2. Casting a mock with as instead of checking it with satisfies. An as cast hides a missing or wrong method, letting the mock drift from the real interface without a single error.
  3. Annotating a mock object with its interface type. The annotation widens the mock and erases the precise recorder types, so argument-level assertions on it stop working.
  4. Skipping tsc in CI because the editor shows errors. The editor is a convenience, not a gate; only a pipeline step actually prevents a regression from merging.
  5. Testing what the types already guarantee. A test asserting a function returns a string duplicates the interlock and adds noise without adding coverage.
  6. Shipping generics with no type-level tests. Without *.test-d.ts assertions, a refactor can silently loosen a public API and every behaviour test still passes.
  7. Trusting a test whose expected value was never verified. A wrong expectation produces a false pass on broken code, so the standard the test measures against must itself be correct.
  8. Using @ts-ignore in a test to make a bad call compile. Where you mean "this call should be rejected", @ts-expect-error asserts the rejection and fails if the error ever disappears.
  9. Enabling type-aware lint rules without the project service. Rules that read the type checker silently do nothing when the linter is given only the syntax tree.

Best Practices

  • Run tsc --noEmit as a required CI step, separate from the build. Treat type checking as its own gate so a build that merely strips types cannot pass for correctness.
  • Order CI cheapest first. Type-check, then lint, then test, then build, so the fastest and broadest check fails first and saves the rest.
  • Write Partial<T> fixture factories. A single factory with defaults means adding a required field breaks one place rather than every test literal.
  • Check mocks with satisfies, not as. It verifies the mock against the contract while keeping the precise types the assertions rely on.
  • Add *.test-d.ts type tests for exported generics. Assert the resolved types of any public generic or conditional so a refactor cannot loosen the API unnoticed.
  • Verify expected values before trusting a green suite. A passing test proves only that the code matches the expectation, so the expectation must be correct in the first place.
  • Turn on the promise-related lint rules. Rules that catch a floating or misused promise find real production bugs that types alone let through.
  • Keep formatting and correctness in separate tools. Let a formatter settle style and the linter enforce correctness so review never argues about layout.

Practice Exercises

  1. The Two Checks. Take a total function, write one type annotation proving it returns a number and one behaviour test proving it returns the right number, and explain in a comment which of the two a wrong-arithmetic bug would trip.
  2. The Fixture Factory. Write an item(over: Partial<CartItem>): CartItem factory with defaults, build two items overriding different fields, and confirm that adding a required field to CartItem breaks only the factory.
  3. The Honest Mock. Build a satisfies-checked mock for a two-method interface with a call recorder, then add a third method to the interface and observe exactly where compilation breaks.
  4. The Suite That Catches a Bug. Write a small case-driven suite for total where one case has a deliberately wrong expected value, run it, and identify from the output whether the fault lies in the code or in the test.