Testing a step alone
What you want to do
The shop's business rules live in its steps: what a charge does when the bank declines, and which parcels the shipping refuses. You want to check each of those rules on its own, with no journey, no real bank and no real carrier.
The code
The program is chapter 26's shop, with export before its workflow and each piece its tests use, and without its run of the day's orders, since importing a module runs its top-level code. Its tests sit beside it, in a file ending in .test.ts, as TypeScript projects usually keep them, and import the shop's pieces and the recorders of Itinera's test support, from itinera/testing. Only tests import itinera/testing, so the program you ship never uses it.
import assert from "node:assert/strict";
import { test } from "node:test";
import { None, Some } from "itinera/option";
import { Contributions, StepEventReporter } from "itinera/testing";
import { string } from "itinera/value";
import {
BookingFailed,
type Carrier,
Charge,
NetworkDown,
type Payments,
RenewCard,
Ship,
} from "./ch27_testing_a_step_alone.js";The steps are the shop's own, unchanged since chapter 26 showed the charge, its rescue step and the shipping. This chapter shows only their tests.
A step meets the outside world only through its services, so the tests bring fakes of their own, implementing Payments and Carrier as chapter 26 declared them, and throwing the errors of chapter 12. Each answers as its test chooses, and implements has TypeScript check that it has every method the service declares:
/**
* A bank for tests: it answers every charge as the test chose, and has
* replaced every card with one named after its holder that expires in 2029.
*/
class TestBank implements Payments {
constructor(private readonly answer: "charges" | "declines" | "is down") {}
async charge(order: string): Promise<string | undefined> {
if (this.answer === "is down") throw new NetworkDown();
if (this.answer === "declines") return undefined;
return `R-${order}`;
}
async replacement(card: string): Promise<string | undefined> {
return `${card.slice(0, card.lastIndexOf("-"))}-2029`;
}
}
/**
* A carrier for tests: it books and collects every parcel, or its booking
* system is down.
*/
class TestCarrier implements Carrier {
constructor(private readonly answer: "works" | "is down") {}
async book(order: string): Promise<string> {
if (this.answer === "is down") throw new BookingFailed();
return `T-${order}`;
}
async collects(): Promise<boolean> {
return true;
}
}Each test is a function given to test, from node:test, Node's own test runner, named after the rule it checks. It fails when it throws, as assert, from node:assert/strict, does when what it checks doesn't hold. The charge is tested by building it with Ann's order, as the executor would, and calling its run. Contributions lends the contributor run asks for, as contributor, and keeps what the step contributes:
/** Ann's charge of 40 to her card. */
function annsCharge(): Charge {
return new Charge("A-1", 40, "ann-2028", false);
}
test("a charge the bank takes gives back the bank's receipt", async () => {
const contributions = new Contributions();
const outcome = await annsCharge().run(
new TestBank("charges"),
contributions.contributor,
);
assert.equal(outcome.kind, "success");
assert.deepEqual(
contributions.read("receipt", string).option(),
Some("R-A-1"),
);
});
test("a charge the bank declines fails with card-expired and no receipt", async () => {
const contributions = new Contributions();
const outcome = await annsCharge().run(
new TestBank("declines"),
contributions.contributor,
);
assert.deepEqual(outcome, {
kind: "failure",
reason: { code: "card-expired" },
});
assert.equal(contributions.read("receipt", string).option(), None);
});
test("a charge lets the error of a bank that is down escape", async () => {
const contributions = new Contributions();
await assert.rejects(
annsCharge().run(new TestBank("is down"), contributions.contributor),
NetworkDown,
);
});The rescue step is built the same way, with the reason the test chooses:
test("renewing an expired card gives back the card that replaced it", async () => {
const contributions = new Contributions();
const renew = new RenewCard("jo-2024", { code: "card-expired" });
const outcome = await renew.run(
new TestBank("charges"),
contributions.contributor,
);
assert.equal(outcome.kind, "success");
assert.deepEqual(
contributions.read("card", string).option(),
Some("jo-2029"),
);
});
test("a failure that is not an expired card is not repairable", async () => {
const contributions = new Contributions();
const renew = new RenewCard("max-2027", { code: "nothing-to-charge" });
const outcome = await renew.run(
new TestBank("charges"),
contributions.contributor,
);
assert.deepEqual(outcome, {
kind: "failure",
reason: { code: "not-repairable" },
});
});The shipping also asks for its step reporter. StepEventReporter lends one, as reporter, and keeps what the step emits through it, in emitted:
/** An order's shipping, for a parcel of this weight. */
function shipping(weight: number): Ship {
return new Ship("A-1", weight, "R-A-1", false);
}
test("a parcel of 2 kg leaves with its receipt", async () => {
const contributions = new Contributions();
const events = new StepEventReporter();
const outcome = await shipping(2).run(
new TestCarrier("works"),
contributions.contributor,
events.reporter,
);
assert.equal(outcome.kind, "success");
assert.equal(
events.emitted[0]?.message,
"the parcel leaves with receipt R-A-1",
);
});
test("a parcel of 90 kg fails with over-parcel-limit before the carrier is called", async () => {
const contributions = new Contributions();
const events = new StepEventReporter();
const outcome = await shipping(90).run(
new TestCarrier("is down"),
contributions.contributor,
events.reporter,
);
assert.deepEqual(outcome, {
kind: "failure",
reason: { code: "over-parcel-limit" },
});
});Once tsc has compiled them, node --test runs the tests, and prints a line for each, with how long it took:
✔ a charge the bank takes gives back the bank's receipt (3.302012ms)
✔ a charge the bank declines fails with card-expired and no receipt (0.408878ms)
✔ a charge lets the error of a bank that is down escape (0.563254ms)
✔ renewing an expired card gives back the card that replaced it (0.321217ms)
✔ a failure that is not an expired card is not repairable (0.279718ms)
✔ a parcel of 2 kg leaves with its receipt (1.136142ms)
✔ a parcel of 90 kg fails with over-parcel-limit before the carrier is called (0.469212ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 225.501803How it works
- A step is an object with a method. The test builds it with
new, giving its constructor the inputs in order, and callsrunwith what its parameters ask for: a service, a contributor, a reporter. Their decorators tell the executor what to give them in a journey; in a test, you give them yourself. The rescue step's@failureReason()gets aReasonfrom the test, an object with acode. - A step is tested through its outcome.
runresolves to the outcome, an object whosekindissuccess,failureorskipped, with itsreasonwhen it has one, whichassert.deepEqualcompares with the one expected. A declined card fails the charge withcard-expired, and a parcel of 90 kg fails the shipping withover-parcel-limit. Its fake carrier is down, so the test passing shows that the shipping refused the parcel without calling it. - What a step contributed is read like the data bag.
Contributions'sreadworks as the data bag's does in chapter 11, and its.option()is compared withSomeorNone, fromitinera/option, the two kinds of chapter 6'sOption. - An error escapes as it would in a journey. When the bank is down, the charge's
runrejects withNetworkDown, which the executor would record as an abnormal termination, as chapter 12 showed.assert.rejectschecks that the promise rejects with an error of that class; what happens next is the workflow's decision, not the step's. - The tests await the steps. These steps are
async, so each test is anasyncfunction that awaitsrun, and Node's test runner awaits the test. A synchronous step is tested the same way, withoutawait. - Recorders lend what the executor would. In a journey, the executor makes a step's contributor and step reporter for each attempt; in a test,
ContributionsandStepEventReporterlend them and keep what they receive. A recorder only keeps what it is given: committing a successful attempt's contributions is the executor's work. - Fakes come from the test, not from the workflow. In a journey, the workflow's providers make the bank and the carriers. Here, the test passes a fake where
runasks for the service, so the step never knows which payment client it got.
So each rule of the shop's steps is checked without running an order. But some rules live in the shop's policies and its workflow: failedShipping, taught in chapter 23 and shown as it is now in chapter 26, deciding that no retry can help and refunding the charge, or the adapter of chapter 21, a method of the workflow class as chapter 23 shows it, taking the weight out of the parcel. These tests never reach them.
Outcomes
We have shown how to test each step alone, with fakes of its services and recorders lending what the executor would.
| The usual way | With Itinera |
|---|---|
| Testing a business rule often means setting up the whole request around it, or mocking the code that calls it. | A step is built from its inputs and run alone, with fakes passed where it asks for services. |
| What a function did is often checked through what the mocks it called received. | A step's test reads the outcome it returned, and what it contributed and emitted. |