Skip to content

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.

FieldTypeDefaultMeaning
signalAbortSignalnoneonce 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 themSAP_SURFACES, else every surface this machine can servewhere to look for sessions
systemstringany"DEV" or "DEV/100": the first session of that system, and client
sessionstringthe first that fitsany 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)
allowTcodesstring[]SAP_ALLOW_TCODESthe only transactions the script may open or work in
blockTcodesstring[]SAP_BLOCK_TCODEStransactions the script may not open or work in
allowSystemsstring[]SAP_ALLOW_SYSTEMSthe only systems ("DEV", "DEV/100") whose sessions are used
allowLogoffbooleanSAP_ALLOW_LOGOFF, else falsemay the script end sessions or the logon (/nex, Log Off)
timeoutnumber5000default timeout of expect and waitFor, in ms
trace{ dir, name, screenshots? }nonerecord 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
verifyVerifyOptionsnoneverified mode: compare each action with a lock file. See Verified mode in a script
envRecord<string, string | undefined>process.envthe environment the defaults above are read from
surfacesSurface[]the real onessurfaces 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 ​

MemberTypeMeaning
historyDone[]every action run so far, in order: { action, code, note, ms, step? }
timeoutnumberthe default timeout of expect and waitFor (the timeout option)
sessionIdstringthe id of the session it works on
policyPolicythe guard's settings in force: write, allowSystems, allowTcodes, blockTcodes, allowLogoff
registryRegistrythe session registry it runs over, the same as the MCP server's
infoSessionInfothe session as last refreshed: surface, system, client, user, transaction, title
traceFilestring | undefinedthe trace file, while one is being written
lockVerifier | undefinedthe verifier, when verified mode is on: its result, and finish(passed)
currentStepstring | undefinedthe 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.

MemberReturnsDoes
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)ControlLocatora field, checkbox, dropdown or button by its id. Short ids work: "VBAK-VBELN", "ctxtVBAK-VBELN", "btn[8]" (Ids and handles)
control(id)ControlLocatorthe same as field, for controls that are not fields
grid(id)GridLocatoran ALV grid, a table control, a tree or a list
status()StatusLocatorthe status bar
button(label)ButtonLocatora 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).

MemberDoes
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 ​

MemberReturnsDoes
step(name, fn)what fn returnsruns 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 returnsruns 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?)stringthe 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).

MemberReturnsDoes
kind"control"what kind of locator it is
sapSapthe session it reads
idstringthe id it was given
toString()stringcontrol <id>, as error messages name it
on(screen)ControlStatethe 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.

MemberReturnsDoes
kind"grid"what kind of locator it is
sapSapthe session it reads
idstringthe id it was given
toString()stringgrid <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.

MemberReturnsDoes
kind"status"what kind of locator it is
sapSapthe session it reads
toString()stringstatus bar
on(screen)StatusStatethe 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.

MemberReturnsDoes
kind"button"what kind of locator it is
sapSapthe session it reads
labelstringthe label it was given
toString()stringbutton "<label>"
find(screen)Controlthe 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)) ​

MatcherPasses 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()) ​

MatcherPasses 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)) ​

MatcherPasses 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) ​

MatcherPasses 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.

MatcherPasses 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 ​

ItemDoes
.notturns 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.

OptionDefaultMeaning
variablesnonevalues for the recording's variables
fallbacknone(drift) => repair or undefined, called only on drift. drift holds test, step (from 1), recorded, phase, failures, screen, remaining, attempt, variables. undefined gives up
maxRepairs5at most this many fallback calls in one run, and 2 per step
savefalsewrite 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.

OptionDefaultMeaning
locknext to file (x.sap.ts → x.sap.lock.json)the lock file. Needed with a function
keythe export's name, else the function's, else "default"the entry in the lock
fallbacknone(drift: Drift) => repair or undefined, called on drift no repair saved in the lock fixes
maxRepairs5at most this many fallback calls, and 2 per action
savetruewrite 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.

OptionDefaultMeaning
lockrequiredthe lock file
key"default"the test's entry in it
mode"verify""verify", "write" or "off": see Lock files
fallbacknone(drift: Drift) => repair or undefined, on drift no saved repair fixes
maxRepairs5at most this many fallback calls in one run, and 2 per action
variablesnonevalues the run was given, which a repair may type
writeEntrythe SDK'show 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 ​

ErrorThrown byMeansWhat to do
Refusedactionsthe guard said no: the action did not run. The message gives the reasondo not look for another way. Let a person do it, or change write or the lists when the system is meant to be changed
ExpectErrorexpect matchersthe 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
Driftactions, reads, expect and sap.lock.finish in verified modeSAP answered otherwise than the lock says. Every later action and read throws the same Driftif 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:

FieldMeaning
step, ordinalthe sap.step block ("" outside any) and which run of it, from 1
actionIndexthe action's place in that block, from 0
phaseact: 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, sitethe SDK line of the action, and file:line where the code ran it
expected, actualthe lock's entry for the action, and the screen and status it led to
screenthe screen now, compact, as an agent reads it
variables, lockthe run's values, and the lock file
attempt, triedfallback calls made for this action, and the repairs tried with why each did not do
toJSON()these fields, for reports

Other exports ​

ExportDoes
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_VERSIONthe 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
Verifierthe 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"

MIT licence. Independent open-source project, not affiliated with, endorsed by or sponsored by SAP SE. SAP and SAP Cloud ALM are trademarks of SAP SE.