<!-- Canonical HTML: https://docs.didro.ai/sap-ui-automation/guides/sdk-tests -->

# Writing tests with the SDK

The npm package is also a TypeScript library (the SDK) and a test runner
for `*.sap.ts` tests. A script attaches to an SAP session you have open,
acts on it with the same actions as `sap_act`, and checks the screen with
assertions that wait. It goes through the same guard as the MCP server:
`SAP_WRITE`, `SAP_ALLOW_SYSTEMS` and the transaction lists apply.

This page is the guide. Every method, option and matcher is in the
[SDK API](https://docs.didro.ai/sap-ui-automation/reference/sdk), and the runner's in the
[Test runner](https://docs.didro.ai/sap-ui-automation/reference/test-runner) reference. The
[tutorial](https://docs.didro.ai/sap-ui-automation/getting-started/tutorial) ends with a test made from a
recording, on your own SAP.

## Set up

The SDK and the test runner import the package, so install it in your
project (Node.js 22.18 or later runs the TypeScript files as they are):

```sh
npm install --save-dev sap-ui-automation
npx sap-ui-automation init         # sap.config.ts, sap-tests/example.sap.ts, skills, MCP clients
npx sap-ui-automation test --list  # what would run
npx sap-ui-automation test         # needs an SAP session open, logged on
```

Without the install, `test` stops with `Cannot find package
'sap-ui-automation'`.

## A script

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

const sap = await connect({ surface: "webgui", system: "ABA" });

await sap.okcode("/nVA03");
await sap.set("VBAK-VBELN", "4711");
await sap.key("Enter");

await expect(sap).toHaveTransaction("VA03");
await expect(sap.field("VBAK-NETWR")).toHaveValue("100.00");
await expect(sap.status()).not.toBeError();

await sap.close();
```

`connect()` never logs on: it attaches to a session that is open now, the
first that fits `surface` and `system`, or the one `session` names. For
targeted work give the exact id from `sap_sessions`. `await using sap =
await connect()` closes it at the end of the block. `write: "off"` makes
every action that may write throw `Refused` instead of running. Every
option: [`connect(options)`](https://docs.didro.ai/sap-ui-automation/reference/sdk#connect-options).

## Act

Each method runs one action, through the guard, and resolves with the
driver's note of what it did (`set wnd[0]/usr/ctxtVBAK-VBELN`); read the screen with
`look()` or a locator. The ids are the ones `sap_look` shows
([Ids and handles](https://docs.didro.ai/sap-ui-automation/concepts/ids)).

| Method | Action |
| --- | --- |
| `okcode(value)` | a command in the command field, submitted (`"/nVA03"`) |
| `set(id, value)` | a field, a checkbox, or a grid cell (with `{ row, col }`) |
| `press(id)`, `click(id)` | a button |
| `key(key)` | a key: a number (0 Enter, 3 Back, 8 F8, 11 Save) or a name (`"Enter"`) |
| `select(id)`, `check(id, value)`, `combo(id, key)` | tabs and rows, checkboxes, dropdowns |
| `f4(id)`, `dblclick(id)`, `focus(id)`, `scroll(id, to)` | value help, double-click, cursor, scrolling |
| `open(app)` | Fiori: a launchpad app by intent (`"#SalesOrder-manage"`) |
| `act({...})` | any action of the [action reference](https://docs.didro.ai/sap-ui-automation/reference/actions) |

An action the guard refuses throws `Refused`; it did not run. `look()`
returns the compact screen as `sap_look` does, `screenshot()` a PNG.

## Assert

`expect` re-reads the screen until the assertion holds or its timeout runs
out (`connect`'s `timeout`, default 5 seconds), then throws `ExpectError`
with what it last saw. Every assertion on a locator or the session takes
`.not` and an optional `{ timeout }`.

| Subject | Assertions |
| --- | --- |
| `sap.field(id)`, `sap.control(id)` | `toHaveValue`, `toContainValue`, `toBeEmpty`, `toBeEditable`, `toBeReadOnly`, `toBeVisible`, `toBeChecked`, `toHaveLabel` |
| `sap.status()` | `toHaveText`, `toContainText`, `toBeSuccess`, `toBeError`, `toHaveType("S"\|"I"\|"W"\|"E"\|"A")`, `toBeEmpty`, `capture(re)` |
| `sap.grid(id)` | `toHaveRowCount`, `toContainText` (optionally in `rows`), `toBeVisible` |
| `sap` | `toHaveTransaction`, `toHaveTitle`, `toBeOnScreen({ program, screen })`, `toContainText` |
| any value | `toBe`, `toEqual`, `toContain`, `toMatch`, `toBeTruthy`, `toBeGreaterThan`, `toBeLessThan`: checked at once, no timeout |

`toHaveValue`, `toHaveText`, `toHaveLabel` and `toHaveTitle` take a whole
string or a regular expression; `toContainValue` and the status bar's
`toContainText` take a string. `expect(sap.status()).capture(re)` waits
until the status bar matches and returns its first group: a number SAP
made, for the steps after it. Each matcher's arguments:
[expect](https://docs.didro.ai/sap-ui-automation/reference/sdk#expect).

> **Row counts of table controls**
>
> On a table control (the classic step loop, such as the items of VA03), SAP
> draws empty lines to fill the visible area, and `toHaveRowCount` counts
> them: an order with one item gives 9 on VA03. On an ALV grid the count is
> the real number of rows. For a table control, check the rows you expect
> instead, with `cell(row, col)` or `toContainText`.
## Steps, and screens SAP shows for some data only

These helpers make a script read like the test a person would write. The
[tidied code of a recording](https://docs.didro.ai/sap-ui-automation/guides/record-replay#tidy-code-from-a-recording)
uses them.

| Method | Does |
| --- | --- |
| `step(name, fn)` | runs `fn` as one named step: its actions carry the name in the trace and in `sap.history`, and an error inside ends with `(in step "name")`. Steps nest |
| `at(place)` | is the session on this screen now? `"SAPLATP4/0500"` (program and screen number), or `{ program, screen, transaction }`. Reads once, never waits |
| `popup()` | the popup in front: `{ title, text }`, or `undefined` |
| `button(label).press()` | presses a button by its label, the popup in front first. A label that several buttons have is refused |
| `save({ acceptWarnings, max })` | key 11, through the guard. With `acceptWarnings`, Enter while the status bar shows a warning, at most `max` times (default 3) |
| `dismissInfo()` | confirms the popup in front only when it informs (text and Continue, no question, no input). `true` when it confirmed one |

```ts
import { expect } from "sap-ui-automation";
import type { Sap } from "sap-ui-automation";
declare const sap: Sap;

await sap.step("Save the order", async () => {
  if (await sap.at("SAPLATP4/0500")) await sap.button("Continue").press();
  await sap.save({ acceptWarnings: true });
  await sap.dismissInfo();
});
const order = await expect(sap.status()).capture(/Order (\d+)/);
console.log(order);
```

## From an agent's run to a script

While a recording is on, every `sap_act` answer has a `code:` line: the
SDK call that repeats the action (`SAP_CODE=on` adds it always,
`SAP_CODE=off` never). `sap_record {"op":"code"}` gives the script so far,
with or without a recording; `{"op":"code","tidy":true}` the tidied test,
with steps and the helpers above. A recording can also be written out as
a script with `export --to sap-ts`, as in the
[tutorial](https://docs.didro.ai/sap-ui-automation/getting-started/tutorial#_8-keep-it-as-code). In a script,
`sap.code()` returns the lines of the run so far, and `sap.draft(name)` a
test file around them.

To keep a task an agent finished as a workflow with inputs and outputs,
which another agent finds and runs again through MCP, see
[Reusable workflows](https://docs.didro.ai/sap-ui-automation/guides/workflows).

## Replaying a verified recording

`runVerified(sap, file, { variables, fallback, save })` replays a recording
known to work, with no model. Only at a step where the screen is not what
the recording expects does it call `fallback` (a model, a person, any
function) for a repair; repairs run under the replay's rules and, with
`save`, go into a new version of the recording.

`runVerified` also runs test code against its [lock file](#lock-files):

```ts
import { connect, type Drift, runVerified } from "sap-ui-automation";

declare function askModel(drift: Drift): Promise<undefined>; // your own: a model, a person, any function

const sap = await connect({ system: "ABA" });
const r = await runVerified(sap, { file: "sap-tests/create.sap.ts", export: "createOrder" },
  { customer: "2200" },
  { fallback: async (drift) => askModel(drift) }); // only for drift no saved repair fixes
console.log(r.passed, r.verified, r.unverified, r.fallbacks, r.repairs, r.patches, r.drift);
```

On drift it pauses inside the run, before anything else happens in SAP,
and awaits `fallback`. A repair runs under the replay's rules (at most 4
actions, no write the action does not make, no leaving the transaction, no
value that is in neither the lock, the parameters nor the screen) and must
land where the lock says. A repair that worked is saved in the lock and
applied with no model the next time the same drift shows. The `.sap.ts`
is never rewritten: `r.patches` proposes the change to the code for a
person to review. Every option: [runVerified](https://docs.didro.ai/sap-ui-automation/reference/sdk#runverified).

## 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's
control, the screen it ran on, and the screen, popup and status it led to.
Typed values are kept but not compared. With a lock, a code run checks
every action as a replay checks a recording, with no model.

- The lock of `<name>.sap.ts` is `<name>.sap.lock.json` next to it. A
  workflow with a `@sap-workflow` header has one lock per revision of its
  source, under `.workflows/`
  ([File formats](https://docs.didro.ai/sap-ui-automation/reference/file-formats#lock-files-sap-lock-json)).
- The runner verifies against the lock by default (`use: { lock: "verify" }`).
  The first pass writes it; later passes rewrite it only when its paths,
  repairs or system change, so a stable lock does not show in diffs.
- Where SAP answers otherwise (another screen, a popup, a new error in the
  status bar), the test fails with a `Drift` error that names the step, the
  action, its line in the file, what the lock expected and what came. Every
  read and action after it throws the same error.
- When the code asks about the screen right after (`sap.at`, `sap.popup`,
  `exists()`, `dismissInfo`, `save({ acceptWarnings })`), a different
  landing is a branch, not drift: the code handles it, and a passing run
  adds that path to the lock. This is how screens SAP shows for some data
  only pass.
- A run on another system or surface than the lock's skips the
  comparison. In `verify` mode paths are only added: delete the lock, or
  its entry, to start again; `--update-locks` replaces the entry of this
  run's system.

| Mode | Does |
| --- | --- |
| `verify` (default) | compare; a passing run adds what the lock does not have |
| `write` | compare nothing, write this run's screens (`npx sap-ui-automation test --update-locks`) |
| `off` | leave the lock alone |

In a script of your own, `connect({ verify: { lock, key } })` compares the
same way, and `await sap.lock?.finish(true)` writes the lock after a pass
(the runner calls it for you): [Verified mode in a
script](https://docs.didro.ai/sap-ui-automation/reference/sdk#verified-mode-in-a-script). Commit lock files
with the tests.

## The test runner

Test files end in `.sap.ts`:

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

test("order 4711 is complete", async ({ sap }) => {
  await sap.okcode("/nVA03");
  await sap.set("VBAK-VBELN", "4711");
  await sap.key("Enter");
  await expect(sap.status()).not.toBeError();
});
```

`test.describe`, `test.skip`, `test.only`, `test.beforeEach`,
`test.afterEach` and `test.use` work as in Playwright; there is no
`beforeAll` or `afterAll`. A `sap.config.ts` sets the defaults:

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

export default defineConfig({
  testDir: "sap-tests",
  timeout: 60_000,
  retries: 0,
  reporter: "list", // list | junit | json | html
  outputDir: "sap-results",
  use: { surface: "webgui", system: "ABA", write: "off", screenshots: true, lock: "verify" },
});
```

Run them:

```sh
npx sap-ui-automation test                     # every *.sap.ts under testDir
npx sap-ui-automation test sap-tests/va03.sap.ts --reporter junit
npx sap-ui-automation test --grep "order" --project s4
npx sap-ui-automation test --list                # what would run
```

- The runner finds `sap.config.ts` (or `.js`, `.mjs`, `.json`) by walking
  up from the current folder; without one, `testDir` is the current
  folder. Every run, `--list` too, imports that config and the test files,
  so their top-level code runs: list and run only projects you trust. Test files and configs load as ES modules even when the
  project's `package.json` says `"type": "commonjs"`.
- The `sap` fixture connects to SAP only for a test or hook that takes it.
  Tests run one at a time: one SAP session is one user's screen.
- A test that passes on a retry is reported as flaky; finding no tests
  exits with 1.
- `--var name=value` gives a workflow's inputs (a file with a
  `@sap-workflow` header): a missing or unknown one fails before the
  runner connects. A test that keeps its values in `const vars`, as
  `export --to sap-ts` writes it, does not read `--var`: change the values
  in the file.
- Node 22.18 or later loads TypeScript as it is; from 22.6 the runner
  re-runs itself with `--experimental-strip-types`, and below that it
  says to use 22.18.

Each test's trace goes to `sap-results/<test>/`; open it with the
[trace viewer](https://docs.didro.ai/sap-ui-automation/guides/trace-viewer). Two things to know about the output in
this version:

- `sap-results/` is not emptied before a run. Traces of tests that no
  longer exist, or of earlier retries, stay next to the new ones. Delete
  the folder first when you want only this run (`rm -rf sap-results`).
- `--reporter` on the command line replaces the config's reporters with
  their default files: `--reporter html` writes `sap-results/index.html`
  even when the config says `["html", { outputFile: "report.html" }]`. Set
  the reporters in the config when you need their `outputFile`.

Every flag, field and fixture: [Test runner](https://docs.didro.ai/sap-ui-automation/reference/test-runner).
In CI, the machine needs an SAP session open, and tests write by default:
set `write` to `off` unless the test system is meant to be changed
([Running in CI](https://docs.didro.ai/sap-ui-automation/guides/ci)).
