Skip to content

Tests & Mutation Lab

The Course
•
15 min study

The project has six grouped runtime tests and six compile-only negative usages. Runtime groups cover normalization/projection, malformed data, dispatch and independent subscriptions, snapshot mutation, disposal, and synchronous exception identity. The consumer also contains valid calls so a useless API that accepts nothing will fail checking.

What needs Node: running the project's own tests needs Node.js 22+ and the download. Everything else on this page, including the exercise, runs in the browser.

Run npm test in the download. It builds declarations, checks consumer.ts through the public export, then runs Node tests through that same export. Never execute consumer.ts: its intentional invalid lines exist only for the checker.

The authoring checks unpack the actual ZIP into a temporary directory, compile it, run its demo and tests, then introduce targeted mutations. Dropping trimming, unsubscribe deletion, snapshot copying or the disposed publish guard must fail runtime evidence. Widening Listener's return to void must make the async-listener directive unused.

Try one mutation at a time and restore it immediately. A failure caused by an unrelated syntax error does not demonstrate that your behavioral test protects the promised rule. Name the observable difference before editing.

Predict, check, and run

Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.

Predict, then runTypeScript
const failure = new Error("listener failed");
let caught: unknown;

try {
  throw failure;
} catch (error) {
  caught = error;
}

console.log(caught === failure);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
true

Predict what each valid mutation should change

Read the public consumer first: every expected-error line should isolate one relationship, while valid calls prove usability. Runtime groups then observe normalization, identity, snapshot order, disposal and thrown error identity. Neither layer can substitute for the other.

Use valid but wrong changes. A no-op unsubscribe should leave an extra callback; live iteration should expose a newly added listener too early. A parse error or a hang is not evidence that a specific contract assertion noticed the intended regression.

Boundary or caseWhat to inspect
Declaration consumerReject raw ids, wrong payloads and unsupported async callbacks
Registration and dispatchObserve independent duplicates and snapshot order
FailurePreserve exact thrown identity and stop later callbacks

Write the expected failed assertion before mutating. Restore source and rebuild declarations between experiments so an old dist artifact cannot contaminate the next observation. Keep the six valid/invalid consumer relationships distinct from runtime behavior groups.

What the project tests look like

You do not need the download to read the tests. This runtime test from gateway.test.mjs feeds malformed records through the public receive and counts subscriber calls. Each record breaks exactly one rule, and a single counter shows that none of them got through:

JavaScript
test("malformed events never reach subscribers", () => {
  const gateway = createGateway();
  let calls = 0;

  gateway.channels.added.subscribe(() => {
    calls++;
  });
  gateway.channels.removed.subscribe(() => {
    calls++;
  });

  for (const raw of [
    null,
    [],
    {},
    { type: "added" },
    { type: "added", payload: null },
    { type: "unknown", payload: { id: "b1" } },
    { type: "added", payload: { id: "b1" } },
    { type: "added", payload: { id: "b1", title: " " } },
    { type: "removed", payload: { id: 1 } }
  ]) {
    assert.equal(gateway.receive(raw).ok, false);
  }

  assert.equal(calls, 0);
});

The compile-only side lives in consumer.ts. Each directive isolates one relationship, imported through the package name as a real consumer would:

TypeScript
// @ts-expect-error a plain string has not passed the id factory
const unchecked: BookId = "b1";

// @ts-expect-error async listeners would return an unsupported Promise
gateway.channels.added.subscribe(async () => {});

The snapshot test is the one the exercise below rebuilds: a listener subscribes a "late" listener during a publish, and the test asserts the late one waits for the next publish.

Build it yourself

Exercise

Tests & Mutation Lab: practice

The workspace has a small channel with a switch: createChannel(true) copies the listeners before publishing (the project's snapshot policy) and createChannel(false) is the mutation, iterating the live Set. Write lateListenerWaits(channel): boolean, a test that passes for the correct channel and fails for the mutated one. Print correct: pass and mutated: fail.

Your workspaceTypeScript
type Channel = {
  subscribe: (listener: () => void) => () => void;
  publish: () => void;
};

function createChannel(snapshot: boolean): Channel {
  const listeners = new Set<() => void>();

  return {
    subscribe(listener) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    publish() {
      // The mutation: iterate the live Set instead of a copy.
      for (const listener of snapshot ? [...listeners] : listeners) {
        listener();
      }
    }
  };
}

// Write lateListenerWaits, then run it against both channels.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

First name the observable difference. With two ordinary listeners both versions call both, so a simple call count cannot tell them apart. The difference appears only when the set of listeners changes during a publish.

Hint 2: a first step

Subscribe a listener that, the first time it runs, subscribes a second "late" listener. Record which listeners ran in one publish and compare the record with what the snapshot policy promises. Guard the nested subscribe with a flag so it happens only once.

Show one solution
One possible solutionTypeScript
type Channel = {
  subscribe: (listener: () => void) => () => void;
  publish: () => void;
};

function createChannel(snapshot: boolean): Channel {
  const listeners = new Set<() => void>();

  return {
    subscribe(listener) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    publish() {
      // The mutation: iterate the live Set instead of a copy.
      for (const listener of snapshot ? [...listeners] : listeners) {
        listener();
      }
    }
  };
}

function lateListenerWaits(channel: Channel): boolean {
  const events: string[] = [];
  let added = false;

  channel.subscribe(() => {
    events.push("first");

    if (!added) {
      added = true;
      channel.subscribe(() => {
        events.push("late");
      });
    }
  });
  channel.publish();

  return events.join(",") === "first";
}

console.log("correct:", lateListenerWaits(createChannel(true)) ? "pass" : "fail");
console.log("mutated:", lateListenerWaits(createChannel(false)) ? "pass" : "fail");

Enable JavaScript to edit and type-check this example.

Text
correct: pass
mutated: fail

A for...of over a live Set also visits entries added during the loop, so the mutated channel calls "late" in the same publish and the record becomes first,late. The copy freezes the list first, so the record is just first. A test that subscribes two listeners and counts calls passes for both versions: it is a valid test of something, but not of this rule. That is the habit the project's mutation lab trains: name the difference, then build the smallest scenario that shows it.

Change it and test it

Extend lateListenerWaits to also check removals: a listener that unsubscribes a later one during publish. Decide from the project comment "already captured removals still run" what the correct record is, and whether the mutated channel differs. In the real project, compare your test with "dispatch snapshots additions and removals during callbacks".

Was this article helpful?

Your response is saved on this device.