# 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](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md)'s shop as a module, with its tests in a file beside it, as in [chapter 27](https://itinera-dev.org/book/typescript/27-testing-a-step-alone.md). 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.

TypeScript, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.test.ts)

```typescript
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](https://itinera-dev.org/book/typescript/19-letting-policies-act-on-the-outside-world.md) does. The workflow is declared as [chapter 23](https://itinera-dev.org/book/typescript/23-undoing-a-charge-when-the-shipping-fails.md) shows it, with the policy `outage` from [chapter 17](https://itinera-dev.org/book/typescript/17-giving-up-a-step-early.md). Its pieces are as [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md) shows the charge, its rescue step, the shipping, `notify` and `failedShipping`, [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md) the lookup, `alreadyCompleted` and the log, [chapter 20](https://itinera-dev.org/book/typescript/20-an-optional-input.md) the pricing and the audit, and [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md) the desk:

TypeScript, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.test.ts)

```typescript
/**
 * 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:

TypeScript, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.test.ts)

```typescript
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:

TypeScript, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.test.ts)

```typescript
/** 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:

TypeScript, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.test.ts)

```typescript
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:

TypeScript, from the program [`ch29_testing_the_flow_with_scripted_steps.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.test.ts)

```typescript
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:

What running the tests of `ch29_testing_the_flow_with_scripted_steps` prints, recorded in [`ch29_testing_the_flow_with_scripted_steps.txt`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch29_testing_the_flow_with_scripted_steps.txt)

```text
✔ 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.194403
```

## How it works

1. **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.
2. **A script names steps by their names in the workflow.** A rescue step is named by its own name, `charge_rescue`. `willFail`, `willTerminateAbnormally` and `willSucceed` end an attempt, and `willContribute` adds a contribution, committed only if the attempt succeeds. An attempt `onAttempt` doesn't name is attempt 1.
3. **The script must cover what can happen.** `run` checks 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 after `over-parcel-limit`.
4. **The run says what each step went through.** `run` resolves to a `ScriptedRun`: its `result` is the result an executor would have given, read as [chapter 25](https://itinera-dev.org/book/typescript/25-reading-the-result.md) does, and `step` gives a step's record. Its `attempts` lists the attempts it had, and `attempt(2)` gives attempt 2 as an `Option`, which `expect` unwraps, as in [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md). An attempt's `input` reads what its step was built with, as the data bag's `read` does: 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.
5. **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. With `over-parcel-limit`, `failedShipping` gives it up, and the result's failure has the cause `FailWorkflow`, with the policy's reason, which `failedByAPolicy` reads once it has compared the cause, as `why` does in [chapter 25](https://itinera-dev.org/book/typescript/25-reading-the-result.md).
6. **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.      |
