Appearance
SDK reference
The npm package is also a TypeScript library. A script attaches to an SAP session that is open now, runs actions on it through the same guard as the MCP server, and checks the screen with assertions that wait. For a walk-through, read Writing tests with the SDK; for *.sap.ts tests, the Test runner reference.
Source: src/sdk/index.ts and the files it exports from.
connect(options)
connect(options?: ConnectOptions): Promise<Sap> attaches to an SAP session that is open now. It never logs on. With session, it takes that session; otherwise the first one found that fits surface and system.
| Field | Type | Default | Meaning |
|---|---|---|---|
signal | AbortSignal | none | once it aborts, no new action is sent: the next one throws the abort reason. SAP may still finish an action already sent |
surface | "sapgui", "webgui", "fiori", or a list of them | SAP_SURFACES, else every surface this machine can serve | where to look for sessions |
system | string | any | "DEV" or "DEV/100": the first session of that system, and client |
session | string | the first that fits | any reference sap_sessions accepts: a list number, an id, a transaction, part of a title. It must also fit surface and system |
write | "on" or "off" | SAP_WRITE, else "on" | actions that may write: run (on) or throw Refused (off) |
allowTcodes | string[] | SAP_ALLOW_TCODES | the only transactions the script may open or work in |
blockTcodes | string[] | SAP_BLOCK_TCODES | transactions the script may not open or work in |
allowSystems | string[] | SAP_ALLOW_SYSTEMS | the only systems ("DEV", "DEV/100") whose sessions are used |
allowLogoff | boolean | SAP_ALLOW_LOGOFF, else false | may the script end sessions or the logon (/nex, Log Off) |
timeout | number | 5000 | default timeout of expect and waitFor, in ms |
trace | { dir, name, screenshots? } | none | record the run as a trace (a .saptest.json named after name, in dir, with step timings and screens); screenshots: true adds a PNG per step. See Trace viewer |
verify | VerifyOptions | none | verified mode: compare each action with a lock file. See Verified mode in a script |
env | Record<string, string | undefined> | process.env | the environment the defaults above are read from |
surfaces | Surface[] | the real ones | surfaces to use instead of the real ones, for tests of your own code |
Lists are not case-sensitive. connect throws an Error when no open session fits: the message lists the sessions open now; open and log on to the session first, or change surface, system or session. It also throws when write is not "on" or "off" ("confirm" and onConfirm were removed), and when a list holds something that is not a transaction code, a Fiori app or a system.
Sap
What connect returns: one SAP session, driven from code. It works on one session id and never moves to another one by itself. You do not construct it yourself.
Properties
| Member | Type | Meaning |
|---|---|---|
history | Done[] | every action run so far, in order: { action, code, note, ms, step? } |
timeout | number | the default timeout of expect and waitFor (the timeout option) |
sessionId | string | the id of the session it works on |
policy | Policy | the guard's settings in force: write, allowSystems, allowTcodes, blockTcodes, allowLogoff |
registry | Registry | the session registry it runs over, the same as the MCP server's |
info | SessionInfo | the session as last refreshed: surface, system, client, user, transaction, title |
traceFile | string | undefined | the trace file, while one is being written |
lock | Verifier | undefined | the verifier, when verified mode is on: its result, and finish(passed) |
currentStep | string | undefined | the step block that runs now; nested names joined with › |
Reading the screen and locators
The locators (field, control, grid, status, button) hold no screen: they read it fresh each time they are used, so they stay valid across actions.
| Member | Returns | Does |
|---|---|---|
look(options?) | Promise<string> | the screen as text, compact by default (what an agent reads). full: true for every id and column; id for one control whole; with id, rows: { from, to } and cols: string[] |
screen() | Promise<ParsedScreen> | the screen parsed, once it has settled: transaction, program, screen, title, status, windows, controls, text |
screenshot() | Promise<Buffer> | a PNG of the session's window or tab |
at(place) | Promise<boolean> | is the session on this screen now? "SAPMV45A/4001" (program and screen number; leading zeros do not count) or { program?, screen?, transaction? }. Only the parts given are compared. Reads once, never waits |
popup() | Promise<{ title, text } | undefined> | the popup in front, with its title and text |
waitFor(f, timeout?) | Promise<ParsedScreen> | re-reads the screen every 200 ms until f(screen) is true. Throws an Error that names the screen when it is not true within timeout ms (default: sap.timeout) |
field(id) | ControlLocator | a field, checkbox, dropdown or button by its id. Short ids work: "VBAK-VBELN", "ctxtVBAK-VBELN", "btn[8]" (Ids and handles) |
control(id) | ControlLocator | the same as field, for controls that are not fields |
grid(id) | GridLocator | an ALV grid, a table control, a tree or a list |
status() | StatusLocator | the status bar |
button(label) | ButtonLocator | a button by its label, in the popup in front first |
Actions
Each action goes through the guard (Safety model) and resolves with the driver's one-line note, such as set wnd[0]/usr/ctxtVBAK-VBELN. more adds fields of the action, as sap_act takes them (Actions reference).
| Member | Does |
|---|---|
act(action) | runs any action sap_act takes: sap.act({ do: "grid", id, row: 0, col: "MENGE", how: "double" }) |
okcode(value) | types a command into the command field: "/nVA03", "/n", "/11" |
set(id, value, more?) | types into a field; value is a string, number or boolean. For a grid cell, more is { row, col } |
press(id, more?) | pushes a button |
click(id, more?) | Fiori: clicks any control by the tail of its UI5 id |
key(key) | a virtual key (0 Enter, 3 Back, 11 Save, 12 Cancel) or a key name ("Enter", "F8", "Control+S") |
select(id, more?) | selects a tab, radio button, menu entry or list item; with { row }, a row of a table or grid |
check(id, value?, more?) | ticks a checkbox, or clears it with false. Default true |
combo(id, key, more?) | picks a dropdown entry by its key or its text |
f4(id, more?) | opens the value help of a field |
dblclick(id, more?) | double-clicks a list entry or a label |
focus(id, more?) | puts the cursor on a control |
scroll(id, to, more?) | scrolls a grid, table control, tree or list to a row, or to "next", "prev", "first", "last" |
open(app) | Fiori: opens a launchpad app by its intent ("#SalesOrder-manage"). Elsewhere it throws ActionError: use okcode("/n<transaction>") |
save(options?) | presses key 11 and returns the status bar (StatusState). With acceptWarnings: true, while the status bar shows a warning (W) it presses Enter, at most max times (default 3); a warning still there after that throws an Error |
dismissInfo() | confirms the popup in front when it only informs (text and Continue, no question, no input), by the rule a replay uses. true when it confirmed one; false, pressing nothing, when there is no popup or it asks something |
An action throws Refused when the guard says no: a write with write: "off", a log off without allowLogoff, a transaction the lists refuse, or any action on the command field other than okcode. In a transaction the lists refuse, only leaving it runs; an action that leads into one is left with /n, then throws. It throws ActionError when it cannot run on this screen (the message says what to do instead), and Drift in verified mode where SAP answers otherwise than the lock says.
Steps, code and lifetime
| Member | Returns | Does |
|---|---|---|
step(name, fn) | what fn returns | runs fn as one named step. Its actions carry the name in the trace and in history; an error thrown inside ends with (in step "name"). Steps nest |
asks(fn) | what fn returns | runs fn as a question about the screen. In verified mode, a landing other than the lock's is then a branch the code handles, not drift. at, popup, dismissInfo, exists() and save({ acceptWarnings }) ask this way |
code() | string[] | the script so far, one SDK line per action: await sap.okcode("/nVA03"); |
draft(name?) | string | the actions so far as a whole *.sap.ts test file. Default name "recorded" |
attach() | Promise<void> | opens the driver and, when asked, starts the trace and verified mode. connect calls it |
useLock(options) | Promise<Verifier | undefined> | turns verified mode on from the next action (VerifyOptions), off (undefined, or mode: "off"), or puts back a Verifier that was on |
close() | Promise<{ trace? }> | ends the trace, if any, and lets the session go. SAP is not touched: the session stays open where it is. Returns the trace's path |
[Symbol.asyncDispose]() | Promise<void> | calls close(): await using sap = await connect() closes it at the end of the block |
ts
import { expect, type Sap } from "sap-ui-automation";
declare const sap: Sap;
await sap.okcode("/nVA01");
const order = await sap.step("Create the order", async () => {
await sap.set("ctxtVBAK-AUART", "OR");
await sap.key("Enter");
await sap.set("ctxtKUAGV-KUNNR", "100001");
await sap.set("txtVBKD-BSTKD", "PO-4471");
await sap.key("Enter");
if (await sap.at("SAPLATP4/0500")) await sap.button("Continue").press();
await sap.save({ acceptWarnings: true });
return await expect(sap.status()).capture(/Standard Order (\d+) has been saved/);
});
console.log(order);ControlLocator
What sap.field(id) and sap.control(id) return. The control is found on each read by its exact id, else as the same field elsewhere on the screen (the lookup a replay uses).
| Member | Returns | Does |
|---|---|---|
kind | "control" | what kind of locator it is |
sap | Sap | the session it reads |
id | string | the id it was given |
toString() | string | control <id>, as error messages name it |
on(screen) | ControlState | the control on a parsed screen, without reading SAP |
state() | Promise<ControlState> | reads the screen: { found, id, type?, label?, value?, editable?, rest? }. found is false when the control is not on the screen; editable is missing when the view does not say |
value() | Promise<string> | a field's text, "true" or "false" for a checkbox, a button's text. Throws an Error when the control is not on the screen |
exists() | Promise<boolean> | is the control on the screen? Asks as sap.asks does |
editable() | Promise<boolean> | true only when the view says the control takes input |
set(value) | Promise<string> | sap.set(id, value) |
press() | Promise<string> | sap.press(id) |
select() | Promise<string> | sap.select(id) |
check(value?) | Promise<string> | sap.check(id, value); default true |
f4() | Promise<string> | sap.f4(id) |
GridLocator
What sap.grid(id) returns: an ALV grid, a table control, a tree or a list. Rows are counted from 0.
| Member | Returns | Does |
|---|---|---|
kind | "grid" | what kind of locator it is |
sap | Sap | the session it reads |
id | string | the id it was given |
toString() | string | grid <id> |
state(range?) | Promise<GridState> | the rows on screen, or rows from to to (the control is scrolled there): { found, id, columns, titles, total?, rows, text }, each row { n, cells, text }. A grid that cannot be read gives found: false; it does not throw |
rowCount() | Promise<number | undefined> | the number of rows the control says it has; undefined when it does not say |
cell(row, col) | Promise<string> | one cell's text, by row and column id or title. A row not on screen is scrolled to. Throws an Error for a row or column it does not have; the message lists the columns |
selectRow(row) | Promise<string> | selects a row |
double(row, col) | Promise<string> | double-clicks a cell; on most reports it opens the document behind it |
setCell(row, col, value) | Promise<string> | types into a cell of a grid that takes input |
scroll(to) | Promise<string> | sap.scroll(id, to) |
On a table control, SAP draws empty lines to fill the visible area, and the count may include them. Check the rows you expect with cell or toContainText instead.
StatusLocator
What sap.status() returns.
| Member | Returns | Does |
|---|---|---|
kind | "status" | what kind of locator it is |
sap | Sap | the session it reads |
toString() | string | status bar |
on(screen) | StatusState | the status bar of a parsed screen: { type?, text } |
state() | Promise<StatusState> | reads the screen. type is S success, I information, W warning, E error or A abort; missing when the view does not say |
text() | Promise<string> | the message, "" when there is none |
type() | Promise<string | undefined> | the message type |
ButtonLocator
What sap.button(label) returns: a button found by its label, for buttons whose id is only a number in a toolbar (wnd[0]/tbar[1]/btn[0]). Within a window it tries the exact label, then the label without the key SAP shows after it (Continue for Continue (Enter)), then either one in any case: in the popup in front first, then anywhere.
| Member | Returns | Does |
|---|---|---|
kind | "button" | what kind of locator it is |
sap | Sap | the session it reads |
label | string | the label it was given |
toString() | string | button "<label>" |
find(screen) | Control | the button on a parsed screen. Throws an Error when no button has the label (the message lists the buttons) or several do (use sap.press with one of the ids it names) |
exists() | Promise<boolean> | is exactly one such button found? Asks as sap.asks does |
press() | Promise<string> | finds the button on the screen now and presses it, through the guard like any action |
expect
expect(subject, options?) picks its matchers by the subject. On a locator or on sap, a matcher re-reads the screen every 200 ms until it holds or options.timeout ms have passed (default: sap.timeout), then throws ExpectError with what it last read. A reading that fails is tried again; a Drift is thrown at once. These matchers also take their own { timeout } as their last argument, and return a promise: await them.
ts
import { expect, type Sap } from "sap-ui-automation";
declare const sap: Sap;
await expect(sap).toHaveTitle(/Display Standard Order 12345/);
await expect(sap.field("ctxtKUAGV-KUNNR"), { timeout: 10_000 }).toHaveValue("100001");
await expect(sap.status()).not.toBeError();
expect(await sap.field("ctxtKUAGV-KUNNR").value()).toMatch(/^\d+$/);A text argument is a string or a regular expression, except where the table says string. A string must equal the whole value (both trimmed) for the toHave... matchers, and be part of it for the toContain... ones.
Controls: expect(sap.field(id))
| Matcher | Passes when |
|---|---|
toHaveValue(text) | the value is text |
toContainValue(string) | the value contains string |
toBeEmpty() | the value is empty or blank |
toBeEditable() | the view says the control takes input |
toBeReadOnly() | the view says the control is read-only |
toBeVisible() | the control is on the screen |
toBeChecked() | the checkbox is ticked |
toHaveLabel(text) | the label is text |
Each needs the control on the screen to pass, so a negated one passes when the control is gone.
Status bar: expect(sap.status())
| Matcher | Passes when |
|---|---|
toHaveText(text) | the message is text |
toContainText(string) | the message contains string |
toBeSuccess() | the type is S |
toBeError() | the type is E or A |
toHaveType(type) | the type is type: "S", "I", "W", "E" or "A" |
toBeEmpty() | there is no message |
capture(re) | the message matches re. Resolves with its first group, or the whole match when re has no group: a number SAP made, for the steps after. It cannot be negated |
Grids: expect(sap.grid(id))
| Matcher | Passes when |
|---|---|
toHaveRowCount(n) | the control says it has n rows; when it does not say, n rows were read |
toContainText(text, { rows? }) | a row read contains text. With rows: { from, to }, those rows are read |
toBeVisible() | the control is on the screen |
Session: expect(sap)
| Matcher | Passes when |
|---|---|
toHaveTransaction(code) | the transaction is code, in any case |
toHaveTitle(text) | the title of the window in front is text |
toBeOnScreen({ program?, screen? }) | the program and screen number are the ones given, spelt as the view shows them (sap.at ignores leading zeros) |
toContainText(text) | the full view of the screen contains text |
Plain values: expect(value)
Any other subject gets matchers that check at once, take no options, and return nothing.
| Matcher | Passes when |
|---|---|
toBe(want) | the value is want (Object.is) |
toEqual(want) | the value and want give the same JSON |
toContain(item) | the string contains item, or the array holds it |
toMatch(re) | the value is a string that matches re |
toBeTruthy() | the value is truthy |
toBeGreaterThan(n) | the value is a number above n |
toBeLessThan(n) | the value is a number below n |
.not and options
| Item | Does |
|---|---|
.not | turns any matcher above around: expect(sap.status()).not.toBeError(). Not on capture, which throws ExpectError |
{ timeout } | ExpectOptions: how long a matcher waits, in ms. On expect(subject, { timeout }) for all its matchers, or as a matcher's last argument for that one |
runVerified
Runs a recording, or code, with no model: it calls fallback only where SAP drifts from what is known to work. It has two forms.
A recording
runVerified(sap, recording, options?): Promise<RunVerifiedResult>, where recording is a .saptest.json path or a parsed test. The replay stops on the first step that drifts and calls fallback; a repair that works is written into a new version of the recording and the replay goes on. A step the guard refuses is never repaired.
| Option | Default | Meaning |
|---|---|---|
variables | none | values for the recording's variables |
fallback | none | (drift) => repair or undefined, called only on drift. drift holds test, step (from 1), recorded, phase, failures, screen, remaining, attempt, variables. undefined gives up |
maxRepairs | 5 | at most this many fallback calls in one run, and 2 per step |
save | false | write the repaired recording back: true for the file it was read from, or a path. Only when the run passed with a repair |
screens | "strict" | "strict": another program or screen number after a step fails it; "loose": it is a warning |
The result: passed, runs (each replay segment), fallbacks (0 when the recording held), changes (the repairs, in words), repaired (the new recording), saved (its path) and ms.
Code
runVerified(sap, code, params, options?): Promise<RunVerifiedCodeResult> runs code(sap, params) in verified mode against its lock. code is a function, or { file, export? } for a module's function export (default "default"; the file's own test(...) declarations are ignored). String and number params are values a repair may type.
| Option | Default | Meaning |
|---|---|---|
lock | next to file (x.sap.ts → x.sap.lock.json) | the lock file. Needed with a function |
key | the export's name, else the function's, else "default" | the entry in the lock |
fallback | none | (drift: Drift) => repair or undefined, called on drift no repair saved in the lock fixes |
maxRepairs | 5 | at most this many fallback calls, and 2 per action |
save | true | write the lock when the run passes |
mode | "verify" | "write" compares nothing and only records, as --update-locks |
A repair is { why, place, actions }: why, in one sentence; place "before", "instead" or "after" the action that drifted; and the actions, as sap_act takes them. It runs under the repair 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 params nor the screen. A repair that works is saved in the lock and applied with no model the next time the same drift shows. The code is never changed: patches proposes the change for a person to review.
ts
import { connect, expect, runVerified, type Sap } from "sap-ui-automation";
async function displayOrder(sap: Sap, p: { order: string }) {
await sap.okcode("/nVA03");
await sap.set("ctxtVBAK-VBELN", p.order);
await sap.key("Enter");
await expect(sap.field("ctxtKUAGV-KUNNR")).toHaveValue("100001");
}
const sap = await connect({ system: "DEV/100", write: "off" });
const r = await runVerified(sap, displayOrder, { order: "12345" }, {
lock: "sap-tests/display-order.sap.lock.json",
fallback: (drift) =>
drift.screen.includes("WINDOW wnd[1]")
? { why: "an information popup before the overview", place: "after", actions: [{ do: "key", key: 0 }] }
: undefined,
});
console.log(r.passed, r.verified, r.unverified, r.fallbacks, r.patches);
await sap.close();The result: passed; value (what the code returned); error and, when drift is why, drift; ms; and the lock's summary: lock, key, mode, verified (actions found as the lock says), unverified (actions the lock had nothing for), fallbacks, repairs, patches, notes and written. An error in the code does not throw: it is in error. A function without lock, or a file without the export, throws before anything runs.
Verified mode in a script
connect({ verify }) or sap.useLock(options) turn verified mode on for a script of your own. The lock is written only by sap.lock.finish(true): the runner calls it after a test passes; a script calls it itself.
| Option | Default | Meaning |
|---|---|---|
lock | required | the lock file |
key | "default" | the test's entry in it |
mode | "verify" | "verify", "write" or "off": see Lock files |
fallback | none | (drift: Drift) => repair or undefined, on drift no saved repair fixes |
maxRepairs | 5 | at most this many fallback calls in one run, and 2 per action |
variables | none | values the run was given, which a repair may type |
writeEntry | the SDK's | how the entry is written; the MCP server sets it. Leave it unset |
ts
import { connect } from "sap-ui-automation";
const lock = "sap-tests/display-order.sap.lock.json";
const sap = await connect({ system: "DEV/100", write: "off", verify: { lock, key: "display order" } });
await sap.okcode("/nVA03");
await sap.set("ctxtVBAK-VBELN", "12345");
await sap.key("Enter");
const summary = await sap.lock?.finish(true); // writes the lock; throws Drift if the last action drifted
console.log(summary?.verified, summary?.unverified, summary?.written);
await sap.close();Errors
| Error | Thrown by | Means | What to do |
|---|---|---|---|
Refused | actions | the guard said no: the action did not run. The message gives the reason | do not look for another way. Let a person do it, or change write or the lists when the system is meant to be changed |
ExpectError | expect matchers | the assertion did not hold: expect(control ctxtKUAGV-KUNNR).toHaveValue("100001"): the value is "100002" (waited 5000 ms) | check the screen in the trace; raise timeout only when SAP is slow |
Drift | actions, reads, expect and sap.lock.finish in verified mode | SAP answered otherwise than the lock says. Every later action and read throws the same Drift | if the new screen is expected (other data, a branch the lock has not seen), run with --update-locks, or mode: "write", to add it |
Refused, ExpectError and Drift are classes: test with instanceof, or by name. An action that cannot run on this screen throws ActionError, which the package also exports.
A Drift names where and what:
| Field | Meaning |
|---|---|
step, ordinal | the sap.step block ("" outside any) and which run of it, from 1 |
actionIndex | the action's place in that block, from 0 |
phase | act: the action could not run; landing: it led elsewhere; check: the screen is the same, with a new error (E or A) in the status bar |
code, site | the SDK line of the action, and file:line where the code ran it |
expected, actual | the lock's entry for the action, and the screen and status it led to |
screen | the screen now, compact, as an agent reads it |
variables, lock | the run's values, and the lock file |
attempt, tried | fallback calls made for this action, and the repairs tried with why each did not do |
toJSON() | these fields, for reports |
Other exports
| Export | Does |
|---|---|
isAt(screen, place) | sap.at on a parsed screen: true when every part place gives matches; false when it gives none |
policyOf(options) | the guard settings connect would use for these options. Throws as connect does on a wrong write or onConfirm |
SDK_VERSION | the SDK's version, written into traces |
codeOf(action, on?) | the SDK statement that repeats an action: await sap.okcode("/nVA03");. on names the variable, default "sap" |
callOf(action, on?) | the same expression without await and ; |
draftTest({ name, lines, from? }) | a whole *.sap.ts file with one test made of these lines. from is where it imports from, default "sap-ui-automation/test" |
bareLabel(label) | a button's label without the key SAP shows after it: "Continue (Enter)" → "Continue" |
findButton(screen, label) | the lookup sap.button uses: { control }, { several }, or {} when none |
parseGrid(text, id) | reads the text of one control, as look({ id }) gives it, into a GridState |
Verifier | the class of sap.lock: result (the summary so far), finish(passed), settle(), key, mode |
LOCK_FORMAT | "sap-gui-lock/1", the format of lock files |
emptyLock() | a lock with no tests |
parseLock(json, file?) | reads a lock's text. Throws an Error that names file when it is not JSON or not a lock |
readLock(file) | the lock at file, or undefined when there is none |
serializeLock(lock) | a lock as the text the SDK writes |
lockPathFor(file) | where a file's lock is: orders.sap.ts → orders.sap.lock.json, x.ts → x.lock.json |
identity(action) | what makes two actions the same action of a step (verb, control, key, row; for okcode the command; not a typed value): "key:0" |
