<!-- Canonical HTML: https://docs.didro.ai/sap-ui-automation/reference/test-runner -->

# Test runner

The package has a test runner for `*.sap.ts` files. A test file imports `test` and
`expect` from `sap-ui-automation/test`; `sap-ui-automation test` finds the files, runs each
test on an SAP session you have open, and reports. The `sap` a test gets is the SDK's
session: see the [SDK reference](https://docs.didro.ai/sap-ui-automation/reference/sdk). For a walk-through, read
[Writing tests with the SDK](https://docs.didro.ai/sap-ui-automation/guides/sdk-tests).

```ts
import { expect, test } from "sap-ui-automation/test";

test.use({ system: "DEV/100", write: "off" });

test.describe("display order", () => {
  test.beforeEach(async ({ sap }) => {
    await sap.okcode("/nVA03");
  });

  test("shows the sold-to party of order 12345", async ({ sap }) => {
    await sap.set("ctxtVBAK-VBELN", "12345");
    await sap.key("Enter");
    await expect(sap).toHaveTitle(/Display Standard Order 12345/);
    await expect(sap.field("ctxtKUAGV-KUNNR")).toHaveValue("100001");
  });

  test("refuses an unknown order", { timeout: 30_000 }, async ({ sap, info }) => {
    test.skip(info.project === "fiori", "VA03 is not a Fiori app");
    await sap.set("ctxtVBAK-VBELN", "99999999");
    await sap.key("Enter");
    await expect(sap.status()).toBeError();
  });
});
```

`sap-ui-automation/test` also exports `ExpectError`, the types below, and the runner as a
library (`runTests`, `testCommand`, `configFor`, `findConfig`, `loadConfig`,
`resolveConfig`, `findTestFiles`, `lockKey`, `reporters` and the report writers).

Source: [`src/runner/`](https://github.com/DidroAI/sap-ui-mcp/blob/main/src/runner/index.ts).

## test

Importing a test file only declares its tests; the runner runs them after, one at a time,
in file order. Calling `test()` outside the runner throws: run the file with
`sap-ui-automation test`.

| Call | Does |
| --- | --- |
| `test(title, fn)` | declares a test. `fn` gets the [fixtures](#fixtures) |
| `test(title, details, fn)` | the same, with `details`: `{ timeout?, use? }` for this test only |
| `test.only(title, [details,] fn)` | when any test or describe is `only`, only those run |
| `test.skip(title, [details,] fn)` | declares a test that is reported as skipped and does not run |
| `test.skip(condition?, reason?)` | inside a test or a `beforeEach` hook: stops the test as skipped when `condition` is true or left out. In a describe body or at the top of a file: skips that group or file |
| `test.describe(title, body)` | groups tests: its title goes into each test's title path, and its hooks and `use` apply to them |
| `test.describe.only(title, body)` | a group that is `only` |
| `test.describe.skip(title, body)` | a group whose tests are skipped |
| `test.beforeEach(fn)` | runs before each test of this file or describe, with the test's fixtures. Outer ones first |
| `test.afterEach(fn)` | runs after each test of this file or describe, even a failed one; inner ones first. Not after a timeout. An error in it fails a test that passed |
| `test.use(options)` | [`use` options](#use) for the tests of this file or describe, over the config's and the project's |
| `test.setTimeout(ms)` | inside a test: its timeout, counted from its start. Elsewhere: the timeout of this file's or describe's tests |
| `test.info()` | the running test's [`info`](#fixtures). Throws outside a test |

There is no `beforeAll` or `afterAll`. A test's `use` is the config's, then its project's,
then each describe's from the outside in, then its own `details.use`: the last one set
wins. Its timeout is `details.timeout`, else the innermost `test.setTimeout`, else the
config's `timeout`; it covers the hooks.

## Fixtures

A test or hook function gets one object, `{ sap, input, output, info }`.

| Fixture | Type | Meaning |
| --- | --- | --- |
| `sap` | `Sap` | the session the test drives, connected from its `use`, with `expectTimeout` as its timeout, a trace in `info.outputDir`, and its [lock](#lock-files). Closed after the test; the SAP session stays open where it is |
| `input(name)` | `(name: string) => string` | the value the caller gave for `name`: `--var name=value`, or `variables` of `sap_workflow_run`. Throws `Missing input "name".` when there is none |
| `output(name, value)` | `(name: string, value: string) => void` | returns a named string to the caller when the test passes. The name must be declared in the file's `@sap-workflow` header, under `outputs`; each name once |
| `info` | `TestInfo` | about the test that runs, below |

The runner connects to SAP only when the test, or a hook of its file or describes, names
`sap` in its parameters: `async ({ sap }) =>`. A function that takes the fixtures whole also
counts. A test that does not ask runs with no SAP session open; using `sap` there throws:
name it in the test's parameters.

| `info` field | Meaning |
| --- | --- |
| `title` | the test's title |
| `titlePath` | the describe titles, then the test's |
| `file` | the test file's path |
| `project` | the project's name, or `undefined` without projects |
| `retry` | 0 on the first run, 1 on the first retry, and so on |
| `outputDir` | this run's own folder: its trace is written there |
| `timeout` | the test's timeout, in ms |

`input` and `output` are for saved workflows: a file whose first line is a
`// @sap-workflow` header with its `description`, `inputs`, `verifies` and, optionally,
`outputs`. In such a file every declared input must be given, not empty, and no other:
else the test fails before it connects.

```ts
// @sap-workflow {"description":"Display a sales order","inputs":{"order":"Sales order number"},"outputs":{"soldTo":"Sold-to party of the order"},"verifies":"VA03 shows the order and its sold-to party"}
import { expect, test } from "sap-ui-automation/test";

test("display order", async ({ sap, input, output }) => {
  await sap.okcode("/nVA03");
  await sap.set("ctxtVBAK-VBELN", input("order"));
  await sap.key("Enter");
  const soldTo = sap.field("ctxtKUAGV-KUNNR");
  await expect(soldTo).not.toBeEmpty();
  output("soldTo", await soldTo.value());
});
```

```sh
npx sap-ui-automation test display-order --var order=12345
```

## defineConfig

`defineConfig(config: SapConfig): SapConfig` returns the config as it is: it only gives it
its type. The runner reads `sap.config.ts`, `sap.config.mjs`, `sap.config.js` or
`sap.config.json`, in that order, from the current folder and then each folder above it;
`--config <file>` names one. A module exports the config as its default export. Without a
config file the defaults below apply, in the current folder. Paths in the config are
relative to the folder the config is in.

```ts
import { defineConfig } from "sap-ui-automation/test";

export default defineConfig({
  testDir: "sap-tests",
  timeout: 60_000,
  retries: 1,
  reporter: ["list", ["junit", { outputFile: "sap-results/junit.xml" }]],
  use: { system: "DEV/100", write: "off", screenshots: true },
  projects: [
    { name: "webgui", use: { surface: "webgui" } },
    { name: "sapgui", use: { surface: "sapgui" } },
  ],
});
```

| Field | Default | Meaning |
| --- | --- | --- |
| `testDir` | the config's folder | where test files are looked for. Folders named `node_modules` or starting with `.`, and `outputDir`, are skipped |
| `testMatch` | `**/*.sap.{ts,js,mjs}` | which files are tests: a glob relative to `testDir` (`**`, `*`, `?`, `{a,b}`), a regular expression, or a list of them |
| `timeout` | `60000` | per test, hooks included, in ms |
| `expectTimeout` | `5000` | how long `expect` waits by default, in ms |
| `retries` | `0` | how often a failing test runs again. A test that passes on a retry is flaky |
| `workers` | `1` | always 1: tests run one after the other, as one SAP session is one user on one screen. Another value is an error |
| `reporter` | `"list"` | a reporter's name, or a list of names and `[name, { outputFile }]`. See [Reporters](#reporters) |
| `outputDir` | `"sap-results"` | where traces and reports go. See [Output](#output) |
| `use` | none | how each test's `sap` is connected, below |
| `projects` | none | named variants of `use`: each test runs once per project, below |

### use

`UseOptions`: the `connect()` options a config, a project, a describe or a test may set.
Only these reach `connect`; `SAP_ALLOW_SYSTEMS`, `SAP_ALLOW_LOGOFF` and the other settings
come from the environment ([Configuration](https://docs.didro.ai/sap-ui-automation/reference/configuration)).

| Field | Default | Meaning |
| --- | --- | --- |
| `surface` | `SAP_SURFACES`, else every surface this machine can serve | `"sapgui"`, `"webgui"`, `"fiori"`, or a list |
| `system` | any | `"DEV"` or `"DEV/100"`: the first open session of that system |
| `session` | the first that fits | any session reference `sap_sessions` accepts |
| `write` | `SAP_WRITE`, else `"on"` | actions that may write: `"on"` runs them, `"off"` refuses them (`Refused`) |
| `allowTcodes` | `SAP_ALLOW_TCODES` | the only transactions the test may open or work in |
| `blockTcodes` | `SAP_BLOCK_TCODES` | transactions the test may not open or work in |
| `screenshots` | `false` | keep a PNG of each step in the trace |
| `lock` | `"verify"` | `"verify"`, `"write"` or `"off"`: see [Lock files](#lock-files) |

### projects

`ProjectConfig`: one variant of `use`, such as the same tests in Web GUI and in SAP GUI.
Without projects, each test runs once.

| Field | Default | Meaning |
| --- | --- | --- |
| `name` | required | the project's name: in `--project`, in reports as `[name]`, and in the lock entry. Names must differ |
| `use` | none | `use` options over the config's `use` |

## Command line

```sh
npx sap-ui-automation test [files or filters] [flags]
```

| Flag | Meaning |
| --- | --- |
| `<filter>` | keeps only test files whose path, relative to the config's folder, contains it, is it, or matches it as a regular expression. Several are allowed. With `--list`, the text is looked for in the file's path |
| `--config <file>` | the config file to use, instead of the nearest one |
| `--project <name>` | runs only this project. A comma-separated list, or repeat the flag. An unknown name is an error that lists the projects |
| `--reporter <names>` | `list`, `junit`, `json`, `html`, comma-separated. Replaces the config's reporters, with their default files |
| `--var <name=value>` | a value for `input(name)`; repeat for several. Values stay strings |
| `--grep <re>` | keeps only tests whose title path, joined with spaces, matches this regular expression |
| `--retries <n>` | how often a failing test runs again, instead of the config's `retries`. A whole number, 0 or more |
| `--list` | prints the tests that would run and connects to nothing. It imports every test file and the `sap.config.*` it finds, at or above the folder, as a run does: their top-level code runs |
| `--update-locks` | lock mode `write` for every test: compare nothing, add this run's screens to the locks |

A flag's value may also follow `=`: `--grep=order`. An unknown flag is an error that prints
the usage; a flag without its value, or a `--var` without `=`, is an error that says so.

```sh
npx sap-ui-automation test                                  # every test under testDir
npx sap-ui-automation test display-order --reporter list,junit
npx sap-ui-automation test --grep "unknown order" --project webgui
npx sap-ui-automation test --list                           # what would run
```

Bun loads TypeScript test files and configs as they are, and so does Node 22.18 or later.
From Node 22.6, the command starts itself again with `--experimental-strip-types`; below
that, `.js` and `.mjs` tests still run, and a `.ts` file fails with a message that says to
use Node 22.18. Test files and configs load as ES modules, even when the project's
`package.json` says `"type": "commonjs"`.

## Reporters

| Reporter | Writes | Default file |
| --- | --- | --- |
| `list` | one line per test as it ends, then each failure with its error, where it failed, the drift and the trace, then the counts | none: prints to the terminal |
| `junit` | JUnit XML for CI servers: one suite per file, one case per test and project. A flaky test passes, with a note; the trace and drift go into `system-out` | `<outputDir>/junit.xml` |
| `json` | the whole result: `rootDir`, `config`, `outputDir`, `tests`, `stats`, `ms`, `startedAt`, `ok`. Each test has its `status`, `attempts`, `error`, `trace`, `drift`, `lock` and `outputs` | `<outputDir>/results.json` |
| `html` | one self-contained page: the counts, then a row per test with its status, time, error and a link to its trace page, written next to each trace | `<outputDir>/index.html` |

`outputFile` is relative to the config's folder. `--reporter` on the command line uses the
default files: set reporters in the config when you need their `outputFile`.

The `list` reporter, for the file at the top of this page with the check
changed to expect the wrong sold-to party (a sample, with made-up data):

```text
  ✘ sap-tests/display-order.sap.ts › display order › shows the sold-to party of order 12345 (7.0s)
  ✓ sap-tests/display-order.sap.ts › display order › refuses an unknown order (1.9s) [3 unverified actions added to the lock]

  1) sap-tests/display-order.sap.ts › display order › shows the sold-to party of order 12345

     expect(control ctxtKUAGV-KUNNR).toHaveValue("100009"): the value is "100001" (waited 5000 ms)
     at sap-tests/display-order.sap.ts:14:48
     trace: sap-results/sap-tests-display-order-display-order-shows-the-sold-to-party-of-order-12345/display-order-shows-the-sold-to-party-of-order-12345.saptest.json

  1 passed, 1 failed (9.0s)
```

A line ends with `flaky, passed on retry 1` for a flaky test, and with what the lock said
when it is worth a look: `[1 repair from the lock, 3 unverified actions added to the lock]`.
A drift adds two lines: the step and action that drifted, and the lock file.

## Lock files

Test code says what to do. A lock file records what the screens looked like on runs that
passed: for each `sap.step` block, each action, the screen it ran on, and the screen, popup
and status it led to. With a lock, each action is checked as a replay checks a recording,
with no model.

- The lock of `display-order.sap.ts` is `display-order.sap.lock.json`, next to it. A file
  with a `@sap-workflow` header has one lock per revision instead: in `.workflows/` next to
  it, named after the file and the SHA-256 of its source. Editing the file starts a new
  lock.
- A test's entry is its title path joined with ` › `, after `[project] ` when there are
  projects: `display order › shows the sold-to party of order 12345`.

| Mode | Does |
| --- | --- |
| `verify` (default) | compares each action with the lock and fails the test with a `Drift` where SAP answers otherwise. A passing test adds what the lock does not have yet, all of it when there is no lock |
| `write` | compares nothing; a passing test adds this run's screens. `--update-locks` sets it for every test |
| `off` | leaves the lock alone |

Set the mode with `use: { lock }` in the config, a project, `test.use` or a test's details;
`--update-locks` wins over all of them.

- An action is compared on its program, screen number and transaction, whether a popup is
  in front, and whether the status bar shows a new error (E or A). The title is not
  compared, nor are typed values.
- When the code asks about the screen right after the action (`sap.at`, `sap.popup`,
  `exists()`, `dismissInfo`, `save({ acceptWarnings })`), a different screen is a branch,
  not drift: the code handles it, and a passing test adds that path to the lock.
- After a `Drift`, every later action and read in the test throws the same error. The
  runner has no fallback: only repairs saved in the lock earlier apply. If the new screen is
  expected, run with `--update-locks` to add it.
- An entry made on another surface or system is not compared and not written in `verify`
  mode; a note in the test's lock report (`json` reporter) says so. In `write` mode the
  entry is replaced.
- The lock is written only when the test passes, and only when something changed: a stable
  lock does not show in diffs. A lock that cannot be written fails the test.

Commit lock files with the tests. To start an entry again, delete it, or the lock.

## Output

The runner does not empty `outputDir` before a run: traces of tests that no longer exist,
or of earlier retries, stay. Delete the folder first when you want only this run.

```text
sap-results/
  junit.xml, results.json, index.html     reports, with their default files
  <test>/                                 one folder per test and project
    <title>.saptest.json                  the trace
    <title>.saptest.html                  its page, with the html reporter
    <title>.trace/step-1.png              with use.screenshots
  <test>-retry1/                          the first retry
```

`<test>` is made of the project's name, the file's path without `.sap.ts`, and the title
path; `<title>` of the title path. Both are in lower case, with `-` for anything that is
not a letter or a digit, and at most 80 characters: the test above writes
`sap-results/sap-tests-display-order-display-order-shows-the-sold-to-party-of-order-12345/`. A
second test with the same folder name gets `-2`. Open a trace with the
[trace viewer](https://docs.didro.ai/sap-ui-automation/guides/trace-viewer).

| Exit code | When |
| --- | --- |
| `0` | no test failed: passed, flaky and skipped tests do not fail the run. With `--list`, every file loaded |
| `1` | a test failed, a file could not be loaded, no tests were found (`No tests found.`), or the config or a flag is wrong |

A file that fails to load is reported as a failed test named `loading <file>`. A test that
runs past its timeout fails: the SAP action in progress cannot be aborted and may still
finish in SAP, so the `afterEach` hooks are skipped and the next test may find SAP still
busy. The teardown (the hooks, writing the lock, closing the session) gets a time of its own,
as long as the test's.
