Testing the flow with scripted steps
What you want to do
You want to check the shop's flow: that a declined card is rescued, that a parcel over the limit is given up after its first attempt, and that a charge ending in an error is never rescued. Each test should say how the steps end, without setting up a bank or a parcel that makes them end that way.
The code
The program is chapter 26's shop as a module, with its tests in a file beside it, as in chapter 27. The tests run the shop's own workflow, whose log prints a line for every event, and Node's test runner shows all a test prints. So the file starts by replacing console.log with a function that prints nothing: mock.method, from node:test, replaces a method of an object, here for every test of the file.
mock.method(console, "log", () => undefined);Each test makes an instance of the shop's workflow for one of Ann's orders, given whole to instance, as chapter 19 does. The workflow is declared as chapter 23 shows it, with the policy outage from chapter 17. Its pieces are as chapter 26 shows the charge, its rescue step, the shipping, notify and failedShipping, chapter 22 the lookup, alreadyCompleted and the log, chapter 20 the pricing and the audit, and chapter 11 the desk:
/**
* An instance of the shop's workflow for one of Ann's orders, of 30, with
* this card and a parcel of this weight.
*/
function order(
order: string,
card: string,
weight: number,
): WorkflowInstance<Orders> {
return Orders.build("email").instance({
order,
customer: "Ann",
price: 30,
parcel: { weight, size: [20, 15, 5] },
card,
giftCard: false,
});
}The first test runs the instance with a script. scripted, from itinera/testing, starts one for an instance. step names a step, and what follows says what its attempts do in place of running it: what they contribute, and how they end. onAttempt moves on to another attempt of the same step, andStep to another step, and run runs the journey, resolving once it has ended:
test("a declined card is renewed and the charge tried again with it", async () => {
const run = await scripted(order("A-1", "ann-2024", 1))
.step("charge")
.willFail("card-expired")
.onAttempt(2)
.willContribute("receipt", "R-A-1")
.willSucceed()
.andStep("charge_rescue")
.willContribute("card", "ann-2029")
.willSucceed()
.andStep("ship")
.willContribute("tracking", "T-A-1")
.willSucceed()
.run();
assert.ok(run.result.isSucceeded());
const retried = run
.step("charge")
.attempt(2)
.expect("the charge's attempt 2");
assert.deepEqual(retried.input("card", string).option(), Some("ann-2029"));
});The next three run one script, whose shipping fails its first attempt with the reason each test chooses; the last reads what the shipping was built with:
/** The reason a policy failed the journey with, if one did. */
function failedByAPolicy(result: JourneyResult): string | undefined {
if (!result.isFailed()) return undefined;
const { failure } = result.status;
if (failure.cause !== "FailWorkflow") return undefined;
return failure.reason.code;
}
/**
* Runs an order of 60 kg whose shipping fails on attempt 1 with this reason,
* and would succeed on attempt 2.
*/
function shippingThatFailsWith(reason: string): Promise<ScriptedRun> {
return scripted(order("A-2", "ann-2028", 60))
.step("charge")
.willContribute("receipt", "R-A-2")
.willSucceed()
.andStep("ship")
.willFail(reason)
.onAttempt(2)
.willContribute("tracking", "B-A-2")
.willSucceed()
.run();
}
test("a shipping that fails with too-heavy is tried again", async () => {
const run = await shippingThatFailsWith("too-heavy");
assert.equal(run.step("ship").attempts.length, 2);
assert.ok(run.result.isSucceeded());
});
test("a shipping that fails with over-parcel-limit is given up after attempt 1", async () => {
const run = await shippingThatFailsWith("over-parcel-limit");
assert.equal(run.step("ship").attempts.length, 1);
assert.equal(failedByAPolicy(run.result), "no-carrier-can-take-it");
});
test("a scripted shipping is still built with the weight the adapter supplies", async () => {
const run = await shippingThatFailsWith("too-heavy");
const first = run.step("ship").attempt(1).expect("the shipping's attempt 1");
assert.deepEqual(first.input("weight", integer).option(), Some(60));
});The next ends the charge's first attempt in an error, as the bank's would:
test("a charge that ends in an error is given up and never rescued", async () => {
const run = await scripted(order("A-3", "ann-2028", 1))
.step("charge")
.willTerminateAbnormally("the payment network is down")
.onAttempt(2)
.willContribute("receipt", "R-A-3")
.willSucceed()
.andStep("charge_rescue")
.willSucceed()
.run();
assert.equal(run.step("charge_rescue").attempts.length, 0);
assert.equal(failedByAPolicy(run.result), "payment-network-down");
});The scripts cover every attempt their steps can have. The last test leaves out the shipping's attempt 2, and checks that run refuses the script with a TestMistake, from itinera/testing, whose message names the attempt left out:
test("a script that leaves out the shipping's attempt 2 is refused", async () => {
const script = scripted(order("A-4", "ann-2028", 1))
.step("ship")
.willFail("too-heavy")
.run();
await assert.rejects(
script,
(mistake) =>
mistake instanceof TestMistake &&
mistake.message === "the test is mistaken: attempt 2 of ship is left out",
);
});With the shop's lines quiet, node --test prints only the tests:
✔ a declined card is renewed and the charge tried again with it (21.719486ms)
✔ a shipping that fails with too-heavy is tried again (10.685514ms)
✔ a shipping that fails with over-parcel-limit is given up after attempt 1 (5.916934ms)
✔ a scripted shipping is still built with the weight the adapter supplies (6.214541ms)
✔ a charge that ends in an error is given up and never rescued (8.398995ms)
✔ a script that leaves out the shipping's attempt 2 is refused (0.957073ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 266.194403How it works
- The script replaces only a step's
run. Every step is still built for real, with its inputs and its services: the shipping's first attempt was built with the weight the adapter supplied, 60. A step the script doesn't name runs for real, as the lookup and the pricing do here. Everything else is the executor's, as in any journey: the hooks, the decisions, the events and the result. - A script names steps by their names in the workflow. A rescue step is named by its own name,
charge_rescue.willFail,willTerminateAbnormallyandwillSucceedend an attempt, andwillContributeadds a contribution, committed only if the attempt succeeds. An attemptonAttemptdoesn't name is attempt 1. - The script must cover what can happen.
runchecks it before the journey starts, and rejects if a scripted step leaves out an attempt it can have, after a retry or a rescue, or can fail on attempt 1 while its rescue step has no script. So some of the other tests script attempts the workflow never reaches, such as the shipping's attempt 2 afterover-parcel-limit. - The run says what each step went through.
runresolves to aScriptedRun: itsresultis the result an executor would have given, read as chapter 25 does, andstepgives a step's record. Itsattemptslists the attempts it had, andattempt(2)gives attempt 2 as anOption, whichexpectunwraps, as in chapter 11. An attempt'sinputreads what its step was built with, as the data bag'sreaddoes: for the charge's attempt 2, the card the rescue step contributed. Attempts that never ran aren't there: the rescue step of the charge that ended in an error has none. - The same script tests one decision of the flow. Two tests run the shipping's script with only its first attempt's reason changed. With
too-heavy, the shipping is retried and the order succeeds. Withover-parcel-limit,failedShippinggives it up, and the result's failure has the causeFailWorkflow, with the policy's reason, whichfailedByAPolicyreads once it has compared the cause, aswhydoes in chapter 25. - A scripted run is awaited like any journey, whatever its steps' execution mode.
So the flow is tested apart from the steps' rules: a change to the charge's rules never breaks these tests, and a change to the workflow is caught by them. But neither kind of test runs one real journey from start to end, with the shop's real steps and its services faked.
Outcomes
We have shown how to test a workflow's flow with scripted steps, checked before the journey runs.
| The usual way | With Itinera |
|---|---|
| Testing what happens after a failure often means making a real dependency fail, or mocking every call the code makes. | A script says how each attempt of a step ends, and the executor runs the rest of the journey as it would. |
| A test of the flow often breaks when a business rule changes. | Scripted steps never run their rules, so a change to those rules never changes what these tests see. |