Get Started & Installation

Tomation Documentation

Get Started & Installation #

Tomation is a browser automation framework with a structured DSL for writing readable UI tests. You author scripts with TypeScript-powered autocomplete, compile them to portable JSON, and run them in the browser via a lightweight extension.

Follow these steps to go from zero to running your first test:

Step 1: Install the Browser Extension

Install the Tomation extension from the Chrome Web Store. This is the runtime that executes your compiled tests directly in the browser with visual step-by-step feedback.

Step 2: Install the Tomation CLI

Install the CLI globally so you can use the tomation command from anywhere:

npm install -g @tomationjs/compiler

Step 3: Scaffold a New Project

Create an empty folder for your tests and run tomation init to generate a starter project with example POM files, tests, and automations:

mkdir my-tests && cd my-tests
tomation init
npm install

This creates a ready-to-use project structure:

my-tests/
├── tomation.config.ts   # Project configuration
├── package.json         # Dependencies (@tomationjs/dsl, @tomationjs/compiler)
├── pom/                 # Page Object Model files (element locators + tasks)
│   ├── login.pom.ts
│   ├── todo.pom.ts
│   └── navigation.pom.ts
├── tests/               # Test files
│   ├── login.test.ts
│   ├── todo.test.ts
│   └── navigation.test.ts
└── automations/         # Parameterized workflows
    └── todo.automation.ts

Step 4: Compile and Run

Compile your DSL files into a .tomation.json file, then load it in the browser extension:

tomation compile

Open the Tomation extension side panel in Chrome, load the generated JSON file, navigate to your app, and run your tests.

Tomation CLI #

The Tomation CLI compiles your TypeScript POM, test, and automation files into a single .tomation.json file that the browser extension can load and execute. The output file name is derived from the meta.name field in your configuration.

Installation

Install the CLI globally to use the tomation command directly:

npm install -g @tomationjs/compiler

Init

Scaffold a new Tomation project with example POM files, tests, and automations:

tomation init

Compile

Run the compile command from your project directory to produce the .tomation.json output file:

tomation compile

Watch Mode

Use watch mode for live recompilation during development. The CLI will automatically recompile whenever your source files change:

tomation watch

Configuration File #

Every Tomation project requires a tomation.config.ts file at the root of the project. This file tells the compiler where to find your source files and how to name the output.

Available configuration fields:

Field Description
meta.name Project name — used for the output filename
meta.urls Array of URLs where tests can run
pom Path to the POM files directory
tests Path to the test files directory
automations Path to automation files directory (optional)
data Path to data files directory (optional)
baseUrl Base path for relative URL resolution

Full configuration example:

// tomation.config.ts
export default {
  meta: {
    name: 'My App Tests',
    urls: ['http://localhost:3000'],
  },
  pom: './pom',
  tests: './tests',
  automations: './automations',
  data: './data',
  baseUrl: './',
}

Element/Locators Builder API #

Tomation uses a fluent builder API to declare element locators. The core pattern is is.TAG.where(matcher).as('Label') — you pick an HTML tag, apply one or more matchers to narrow the selection, and give it a human-readable label.

Basic Element Declaration

Any uppercase HTML tag name works with the is builder: is.INPUT, is.BUTTON, is.DIV, is.FORM, is.SELECT, etc.

import { is, idIs, innerTextIs, classIncludes, placeholderIs, nameIs, typeIs } from '@tomationjs/dsl'

const submitButton = is.BUTTON.where(idIs('submit-btn')).as('Submit Button')
const emailInput = is.INPUT.where(nameIs('email')).as('Email Input')
const heading = is.H1.where(innerTextIs('Welcome')).as('Page Heading')

Scoping with childOf

Use .childOf(parent) to scope the element search within a parent element. This is useful when you have multiple elements with the same matcher on the page but need to distinguish them by their container. The .childOf() and .where() methods can be chained in any order.

const loginForm = is.FORM.where(idIs('login-form')).as('Login Form')
const submitButton = is.BUTTON.where(innerTextIs('Submit')).childOf(loginForm).as('Login Submit')

const signupForm = is.FORM.where(idIs('signup-form')).as('Signup Form')
const signupSubmit = is.BUTTON.where(innerTextIs('Submit')).childOf(signupForm).as('Signup Submit')

XPath Elements

For complex selectors that go beyond tag + matcher combinations, use the Element() function with an XPath expression:

import { Element } from '@tomationjs/dsl'

const alert = Element('//div[@role="alert"]').as('Alert Box')
const thirdRow = Element('//table/tbody/tr[3]').as('Third Row')

Navigate (Relative DOM Traversal)

Use .navigate(path) to enable relative DOM traversal from an anchor element. First, the anchor element is located using the standard tag + matcher logic, then the runtime traverses the DOM following the comma-separated path of navigation steps to reach the final target element. This is useful for locating elements that lack unique identifiers but are positioned predictably relative to an identifiable anchor.

Supported navigation steps:

StepDescription
parentTraverses to the parent element
child[n]Traverses to the nth child element (1-based)
firstChildTraverses to the first child element
lastChildTraverses to the last child element
nextSiblingTraverses to the next sibling element
prevSiblingTraverses to the previous sibling element
sibling[n]Traverses to the nth sibling (1-based, via parent's children)

Usage examples:

import { is, idIs, innerTextIs } from '@tomationjs/dsl'

// Navigate from an anchor element to a nearby target
const target = is.DIV.where(idIs('anchor')).navigate('parent,child[2]').as('Target')

// Combine with childOf for scoped anchor + navigation
const container = is.DIV.where(idIs('section')).as('Section')
const content = is.SPAN.childOf(container).where(innerTextIs('Header')).navigate('nextSibling').as('Content')

Table Cell Accessors

Define a table once as a normal is.TABLE locator, then reach a single cell at the point of use with the .cell(row, column), .firstRow(column), and .lastRow(column) accessors. Rows and columns are 1-based.

AccessorDescription
cell(row, column)Cell at an explicit 1-based row and column
firstRow(column)Cell in the first row at the given column
lastRow(column)Cell in the last row at the given column

Each of row and column accepts a cell selector: a 1-based number, the symbolic first/last, or an object { tag?, index } to narrow how rows or cells are counted. Column also accepts a named/enum value — a const object property such as UsersColumn.Email — which resolves to a numeric index while preserving the name for display.

Usage examples:

import { is, idIs } from '@tomationjs/dsl'

// Define the table once
const UsersTable = is.TABLE.where(idIs('users')).as('Users')

// Reach cells at the point of use (1-based row and column)
Click(UsersTable.cell(2, 3))
Click(UsersTable.firstRow(2))
Click(UsersTable.lastRow(3))

// Named columns keep tests readable and stable
const UsersColumn = { Name: 1, Email: 2, Status: 3 } as const
AssertHasText(UsersTable.cell(2, UsersColumn.Email), 'john@example.com')

// Object form narrows how rows/cells are counted by tag
Click(UsersTable.cell({ tag: 'tr', index: 2 }, { tag: 'td', index: 3 }))

Counting rules:

Where Matchers #

The .where() method accepts matcher functions that narrow down element selection by matching on attributes, text content, position, or state. You can combine multiple matchers to create precise locators.

MatcherMatches onExample
idIs(value)Element id attributeis.INPUT.where(idIs('username'))
innerTextIs(value)Exact text contentis.BUTTON.where(innerTextIs('Login'))
innerTextContains(value)Partial text contentis.DIV.where(innerTextContains('Welcome'))
classIncludes(value)CSS class nameis.LI.where(classIncludes('active'))
placeholderIs(value)Input placeholderis.INPUT.where(placeholderIs('Enter email'))
nameIs(value)Element name attributeis.INPUT.where(nameIs('password'))
typeIs(value)Input type attributeis.INPUT.where(typeIs('checkbox'))
valueIs(value)Element value propertyis.INPUT.where(valueIs('hello'))
ariaLabel(value)aria-label attributeis.BUTTON.where(ariaLabel('Close'))
roleIs(value)role attributeis.DIV.where(roleIs('dialog'))
titleIs(value)title attributeis.A.where(titleIs('Submit form'))
hrefContains(value)Substring of hrefis.A.where(hrefContains('/login'))
isDisabled()Element is disabledis.BUTTON.where(isDisabled())
isNthElement(n)N-th matching element (1-based)is.LI.where(isNthElement(3))
dataAttr(name, value)data-* attributeis.DIV.where(dataAttr('testid', 'submit'))
closestLabelIs(tag, text)Nearby label elementis.INPUT.where(closestLabelIs('LABEL', 'Email'))

User Functions: Click, Type, Select #

User functions simulate real user interactions with the page. They operate on element locators declared via the builder API and form the core of every test step.

Interaction Functions

Click(element) — Click on an element. Works with buttons, links, checkboxes, or any clickable target.

Type(value).in(element) — Type text into an input or textarea field.

TypePassword(value).in(element) — Type a password into an input. The value is masked in logs for security.

Select(value).in(element) — Select an option from a dropdown (<select>) element by its visible text.

import { Click, Type, TypePassword, Select } from '@tomationjs/dsl'

// Click a button
Click(submitButton)

// Type into an input field
Type('user@example.com').in(emailInput)

// Type a password (value masked in logs)
TypePassword('s3cretP@ss').in(passwordInput)

// Select a dropdown option
Select('Admin').in(roleDropdown)

Save to Context #

Save functions capture runtime values from the page and store them in a shared context object. Saved values can be referenced later in the same test in two ways: the typed ctx.keyName object (recommended — gives you autocomplete) or the {{ctx.keyName}} string interpolation syntax. Both resolve to the same saved value at runtime.

SaveText(element).as('key') — Save the element's text content to context.

SaveAttribute(element, 'attr').as('key') — Save a specific attribute value from the element.

SaveValue(element).as('key') — Save an input element's current value.

Save(expression).as('key') — Save a computed expression or literal value to context.

import { ctx, SaveText, SaveAttribute, SaveValue, Save, Type, Navigate } from '@tomationjs/dsl'

// Save the text content of an element
SaveText(welcomeMessage).as('greeting')

// Save a specific attribute
SaveAttribute(profileLink, 'href').as('profileUrl')

// Save an input's current value
SaveValue(searchInput).as('lastSearch')

// Save a computed expression
Save('2024-01-15').as('targetDate')

// Reference saved values with the typed ctx object (recommended)
Type(ctx.greeting).in(noteInput)
Navigate(ctx.profileUrl)

// Or with the {{ctx.key}} string interpolation form
Type('{{ctx.greeting}}').in(noteInput)

Saved context values can also be used in if-conditions to branch test logic based on runtime state:

import { ctx, SaveText, Click } from '@tomationjs/dsl'

SaveText(statusBadge).as('status')
if (ctx.status === 'Pending') {
  Click(approveButton)
}

AssertThat — String Equality Assertion

AssertThat(actual).isEqual(expected) asserts that a resolved string value equals an expected string. Both actual and expected may be plain string literals or strings containing {{ctx.*}}, {{data.*}}, or task parameter tokens. This is the natural companion to ApiCall.save(...) and .saveStatus(...) for verifying values saved to context.

import { Test, ApiCall, AssertThat } from '@tomationjs/dsl'

// Verify a saved API response code
Test('API returns correct status code', () => {
  ApiCall('https://api.example.com/users/123')
    .method('GET')
    .status(200)
    .saveStatus('responseCode')

  // Assert the saved status code equals '200'
  AssertThat('{{ctx.responseCode}}').isEqual('200')
})

// Compare saved value against expected value with tokens
Test('Saved context value matches expected value', () => {
  ApiCall('https://api.example.com/data')
    .jsonBody({ id: 42 })
    .save('userId', 'data.id')

  // Compare saved value against expected value
  AssertThat('{{ctx.userId}}').isEqual('42')
})

Arguments: Both actual and expected may be:

Token resolution: At runtime, all tokens in both actual and expected are resolved to their string values. The comparison is exact and case-sensitive — no trimming or coercion.

Failure handling: The step fails if a token cannot be resolved (missing context key, data path, or parameter) or if the resolved strings do not match. The error message contains both the resolved actual and expected values for debugging.

Date Helpers #

Date helpers generate formatted date strings relative to the current date. They are useful for filling date inputs with dynamic values that stay correct over time. All helpers accept an optional format string (default: YYYY-MM-DD).

Available helpers: today(), tomorrow(), yesterday(), nextWeek(), lastWeek(), nextMonth(), lastMonth(), firstDateOfMonth(offset), lastDateOfMonth(offset).

import { today, tomorrow, yesterday, nextWeek, lastWeek, nextMonth, lastMonth, firstDateOfMonth, lastDateOfMonth } from '@tomationjs/dsl'

// Default format: YYYY-MM-DD
Type(today()).in(dateInput)
Type(tomorrow()).in(dueDateInput)
Type(yesterday()).in(startDateInput)

// Week and month offsets
Type(nextWeek()).in(scheduledInput)
Type(lastMonth()).in(reportDateInput)

// Custom format
Type(today('DD/MM/YYYY')).in(localeDateInput)
Type(nextWeek('MM-DD-YYYY')).in(usDateInput)

// First and last date of month (offset: 0 = current, 1 = next, -1 = previous)
Type(firstDateOfMonth(0)).in(periodStartInput)
Type(lastDateOfMonth(0)).in(periodEndInput)
Type(firstDateOfMonth(1)).in(nextPeriodStartInput)

Keyboard Actions #

Simulate key presses on the focused element or a targeted element. Use shortcuts for common keys, or the generic PressKey / Press for any key with modifier support.

Shortcut functions (press on the currently focused element):

FunctionKey dispatched
PressEnter()Enter
PressTab()Tab
PressEsc()Escape
PressSpace()Space
PressUp()ArrowUp
PressDown()ArrowDown
PressLeft()ArrowLeft
PressRight()ArrowRight

Generic functions:

FunctionDescription
PressKey(key, options?)Press any key on the focused element. Accepts optional modifiers.
Press(key, options?).in(element)Press a key on a specific targeted element.

Modifiers — the optional options object:

{ ctrl?: boolean, alt?: boolean, meta?: boolean, shift?: boolean }

import { PressKey, Press, PressEnter, PressTab, PressEsc } from '@tomationjs/dsl'

// Shortcuts — press on focused element
PressEnter()
PressTab()
PressEsc()

// Generic — any key with modifiers
PressKey('a', { ctrl: true })       // Ctrl+A (select all)
PressKey('s', { meta: true })       // Cmd+S (save)
PressKey('Delete')                  // Delete key

// Targeted — press on a specific element
Press('Enter').in(searchInput)
Press('ArrowDown', { alt: true }).in(dropdown)

Test Data & Fake Generators #

Define reusable data templates with Data() and generate realistic random values using Fake generators. Each test run produces fresh values — no more hardcoded strings.

Defining a Data Template

Create a .data.ts file and use Data() to declare a template with static values and Fake generator calls:

// data/user.data.ts
import { Data, Fake } from '@tomationjs/dsl'

const user = Data({
  name: Fake.fullName(),
  email: Fake.email(),
  phone: Fake.phone({ country: 'US' }),
  dob: Fake.dateOfBirth({ minAge: 18, maxAge: 65, format: 'MM/DD/YYYY' }),
  role: Fake.oneOf(['Admin', 'Editor', 'Viewer']),
  address: Fake.address(),
  id: Fake.uuid(),
  notes: Fake.sentence(),
})

export default user

Using Data in Tests

Import the data template and reference its properties directly. The compiler resolves them to {{data.templateName.property}} tokens, and the runtime generates fresh values each run:

// tests/registration.test.ts
import { Test, AssertHasText } from '@tomationjs/dsl'
import user from '~/data/user.data'
import Form from '~/pom/registration.pom'

Test('Register with generated data', () => {
  Form.fillForm({
    name: user.name,
    email: user.email,
    phone: user.phone,
  })
  Form.submit()
  AssertHasText(Form.message, 'Registration successful')
})

Inline Data

You don't have to keep every template in a separate .data.ts file. For data that only one file needs, declare Data() inline at the top level of a .test.ts or .automation.ts file, right next to the tests that use it. The data name defaults to the variable name:

// tests/todo.test.ts
import { Test, Type, Click, AssertExists, AssertHasText, Data, Fake } from '@tomationjs/dsl'
import Todo from '~/pom/todo.pom'

// Inline template — the data name defaults to the variable name `task`.
const task = Data({
  title: 'Write report',
  detail: { priority: 'high' },
  note: Fake.fullName(),
})

Test('Add todo items from inline data', () => {
  // Compiles to {{data.task.title}}
  Type(task.title).in(Todo.input)
  Click(Todo.addButton)
  AssertExists(Todo.firstItem)
  // Assertion expected value also compiles to {{data.task.title}}
  AssertHasText(Todo.firstItemText, task.title)
})

Renaming Inline Data with .as()

Chain .as(name) onto an inline Data() to override the data name independently of the variable name. The override becomes the first segment of the emitted token:

// Variable is `label`, but the data name is overridden to `groceries`.
const label = Data({ text: 'Buy groceries' }).as('groceries')

Test('Add a labelled item', () => {
  // Referenced as label.text, compiles to {{data.groceries.text}}
  Todo.addItem({ text: label.text })
  AssertHasText(Todo.list, label.text)
})

Nested Property Access

Reference nested properties with regular dot access. The compiler walks the full path and emits a matching {{data.<name>.<path>}} token — any depth is supported. Fake.* leaves are emitted as tokens too (never inlined), so each run gets fresh values:

// Given: const task = Data({ detail: { priority: 'high' }, note: Fake.fullName() })

// Nested path → {{data.task.detail.priority}}
Type(task.detail.priority).in(Todo.input)

// Fake.* leaf → {{data.task.note}} (resolved to a fresh value at run time)
Todo.addItem({ text: task.note })

Note: Inline Data() is purely additive — it compiles to the same {{data.*}} tokens and resolved data object as the shared .data.ts + import flow. The existing shared-file approach is unchanged, and you can mix inline and imported data freely in the same file.

Fake Generator Reference

MethodDescriptionOptions
Fake.firstName(gender?)Random first name'male' | 'female'
Fake.lastName()Random last name—
Fake.fullName(gender?)First + last name'male' | 'female'
Fake.email()Random email address—
Fake.phone(options?)Phone number by country{ country: 'US'|'UK'|'ES' }
Fake.dateOfBirth(options?)DOB with age constraints{ minAge, maxAge, format }
Fake.address(part?)Address or component'full'|'street'|'city'|'country'|'zip'
Fake.oneOf(values)Pick from arraystring[]
Fake.number(options?)Random number{ min, max, decimals }
Fake.uuid()UUID v4 string—
Fake.sentence(options?)Random sentence{ minWords, maxWords }
Fake.pastDate(options?)Date in the past{ within (days), format }
Fake.futureDate(options?)Date in the future{ within (days), format }
Fake.sequence(options?)Sequential counter{ prefix, pad }

Reproducible Data with Seed

Pin a seed to generate the same values every run — useful for reproducing failures:

const user = Data({
  name: Fake.fullName(),
  email: Fake.email(),
}, { seed: 42 })  // Same values every run

You can also pin/unpin seeds from the extension UI in the Test Data panel without editing code.

Configuration

Add a data property to your tomation.config.ts to specify where data files are located:

export default {
  meta: { name: 'My App', urls: ['http://localhost:3000'] },
  pom: './pom',
  tests: './tests',
  data: './data',  // ← data files directory
  baseUrl: './',
}

Enums & Const Maps #

For hardcoded data that doesn't change between runs, use TypeScript enum declarations or const object maps. The compiler resolves member references at build time into their literal string values.

Using an enum:

// data/skills.enum.ts
enum TechSkill {
  JavaScript = 'JavaScript',
  TypeScript = 'TypeScript',
  Python = 'Python',
  React = 'React',
  NodeJS = 'Node.js',
}

export default TechSkill

Using a const map:

// data/skills.ts
const TechSkill = {
  JavaScript: 'JavaScript',
  TypeScript: 'TypeScript',
  Python: 'Python',
  React: 'React',
  NodeJS: 'Node.js',
} as const

export default TechSkill

Using in tests or automations:

import TechSkill from '~/data/skills.enum'
// or: import TechSkill from '~/data/skills'

// Resolved at compile time to the literal value "TypeScript"
Select(TechSkill.TypeScript).in(skillsDropdown)

Both forms work the same way: the compiler reads the enum or const map at build time and replaces TechSkill.TypeScript with "TypeScript" in the output JSON. This keeps your test code readable while avoiding magic strings.

Conditionals in Tasks #

Tasks support conditional logic using standard if statements. The condition must reference a parameter from the task's params object. Steps inside the if block only execute when the condition is met at runtime.

Supported condition patterns:

PatternMeaning
if (param)Truthy — execute when param is provided / non-empty
if (!param)Falsy — execute when param is absent / empty
if (param == true)Boolean truthy — same as if (param)
if (param == false)Boolean falsy — same as if (!param)
if (param === 'value')Equals — execute when param matches a specific string
if (param !== 'value')Not equals — execute when param does not match

Example — optional steps based on boolean params:

import { Task, Click } from '@tomationjs/dsl'

const applyFilters = Task((params: { unreviewed?: boolean, archived?: boolean }) => {
  const { unreviewed, archived } = params
  Click(clearAllButton)
  if (unreviewed == true) {
    Click(unreviewedCheckbox)
  }
  if (archived == true) {
    Click(archivedCheckbox)
  }
}).as('Apply Filters')

Example — branching on a string param:

const selectRole = Task((params: { role: string }) => {
  const { role } = params
  if (role === 'admin') {
    Click(adminRadio)
  }
  if (role === 'viewer') {
    Click(viewerRadio)
  }
}).as('Select Role')

Note: For param-based conditions, the identifier must be destructured from params. else blocks are not supported — use a separate if with the negated condition instead. Both == and === are accepted.

Context-Based Conditionals

You can also branch based on values saved to the runtime context using SaveText, SaveAttribute, SaveValue, or Save. Use the ctx object in the condition — it references values that were saved earlier in the test run.

Supported context condition patterns:

PatternMeaning
if (ctx.key)Truthy — execute when the saved value is non-empty
if (!ctx.key)Falsy — execute when the saved value is empty or not set
if (ctx.key === 'value')Equals — execute when the saved value matches
if (ctx.key !== 'value')Not equals — execute when the saved value doesn't match

Example — conditional steps based on a saved value:

import { ctx, SaveText, Click, Test } from '@tomationjs/dsl'

Test('Toggle status based on current state', () => {
  SaveText(statusLabel).as('currentStatus')
  if (ctx.currentStatus === 'Active') {
    Click(deactivateButton)
  }
  if (ctx.currentStatus === 'Inactive') {
    Click(activateButton)
  }
})

Important: Context conditions are evaluated at runtime — the SaveText (or similar) step must execute before the if (ctx.key) condition is reached. If the key has not been saved yet, the condition evaluates as falsy.

The When() Helper

When(condition, () => { ... }) is a functional-style alternative to an if block. It accepts the same param- and context-based conditions and behaves identically at runtime — it's purely a matter of style. The callback holds the steps to run when the condition is met.

import { When, ctx, Click, Type } from '@tomationjs/dsl'

// Block body — group multiple steps under one condition
When(ctx.status === 'Active', () => {
  Click(deactivateButton)
  Type('archived').in(reasonInput)
})

// Concise body — a single step
When(unreviewed, () => Click(unreviewedCheckbox))

The equivalent if form is exactly the same — use whichever reads better for your team:

if (ctx.status === 'Active') {
  Click(deactivateButton)
  Type('archived').in(reasonInput)
}

Conditionals in the Execution Log

Both if and When conditions show up as their own rows in the execution log, so you can see each branch decision as the test runs. A condition row displays the evaluated expression and whether the branch was taken:

If ctx.status equals "Active"   ✓ condition met
   Click Deactivate Button      ✓
If unreviewed is set            ⊘ skipped

Assertions #

Assertion functions verify that the page is in the expected state after user interactions. They fail the test immediately if the condition is not met.

AssertExists(element) — Asserts that an element exists in the DOM and is visible.

AssertNotExists(element) — Asserts that an element does NOT exist or is not visible.

AssertHasText(element, expectedText) — Asserts that an element's text content matches the expected string.

import { AssertExists, AssertNotExists, AssertHasText } from '@tomationjs/dsl'

// Verify element exists
AssertExists(Login.submitButton)

// Verify element does not exist (e.g., error message hidden)
AssertNotExists(Login.errorMessage)

// Verify text content
AssertHasText(Login.message, 'Login successful')

AssertThat — String Equality Assertion

AssertThat(actual).isEqual(expected) asserts that a resolved string value equals an expected string. Both actual and expected may be plain string literals or strings containing {{ctx.*}}, {{data.*}}, or task parameter tokens. This is the natural companion to ApiCall.save(...) and .saveStatus(...) for verifying values saved to context.

import { Test, ApiCall, AssertThat } from '@tomationjs/dsl'

// Verify a saved status code
ApiCall('https://api.example.com/users/123')
  .method('GET')
  .status(200)
  .saveStatus('responseCode')

AssertThat('{{ctx.responseCode}}').isEqual('200')

// Verify a saved response value
ApiCall('https://api.example.com/data')
  .jsonBody({ id: 42 })
  .save('userId', 'data.id')

AssertThat('{{ctx.userId}}').isEqual('42')

// Compare against a plain string or dynamic expected value
AssertThat('static-value').isEqual('static-value')
AssertThat('{{ctx.savedValue}}').isEqual('{{data.expectedValue}}')

Token resolution — Both actual and expected are resolved at runtime:

Failure behavior — The step fails if a token cannot be resolved (missing context key, data path, or parameter) or if the resolved strings do not match exactly (case-sensitive, no trimming). The error message contains both the resolved actual and resolved expected values for debugging.

Network Request Assertions #

AssertRequest(url?) verifies that the page made (or did not make) an XHR/fetch network request matching a set of criteria. During a run, Tomation captures the requests the page fires and evaluates the assertion against that captured set — no network mocking or interception is involved. Chain refinement methods to narrow what counts as a match, then finish with an expectation.

The optional first argument matches the request URL. Pass a string for an exact match, a RegExp to match by pattern, or { glob: '...' } for wildcard matching. Omit it to match on the other criteria alone.

MethodDescription
.method(m)Match the HTTP method (case-insensitive), e.g. 'GET', 'POST'.
.query(pairs)Match query-string parameters as a subset — the request may carry extra params.
.jsonBody(obj)Match a JSON request body as a structural subset.
.formBody(pairs)Match a URL-encoded form body as a subset of key/value pairs.
.rawBody(str)Match the request body as an exact raw string.
.status(s)Match the response status: an exact code (200), a class shorthand ('2xx'), or a range ({ min: 200, max: 299 }).
.notMade()Expectation: assert that no request matched. Passes when the match count is zero.
.times(n)Expectation: assert that exactly n requests matched.

With no .notMade() or .times(), the default expectation is "at least one matching request".

import { AssertRequest } from '@tomationjs/dsl'

const API = 'https://api.example.com'

// A GET with a query param returned 200
AssertRequest(`${API}/posts`).method('GET').query({ userId: '1' }).status(200)

// A POST created a resource (201) with a matching JSON body subset
AssertRequest(`${API}/posts`).method('POST').jsonBody({ title: 'Hello' }).status(201)

// Match by pattern / glob instead of an exact URL
AssertRequest(/\/posts\/\d+$/).method('GET').status('2xx')
AssertRequest({ glob: `${API}/users/*` }).method('GET')

// Negative and count expectations
AssertRequest({ glob: `${API}/posts/*` }).method('DELETE').notMade()
AssertRequest(`${API}/posts`).method('POST').times(1)

Trigger the request first (for example with a Click), give it a moment to complete with Wait if needed, then assert:

Test('Loading posts calls the API', () => {
  Click(Page.loadPostsButton)
  Wait(800)
  AssertRequest(`${API}/posts`).method('GET').query({ userId: '1' }).status(200)
})

Note: network capture uses the Chrome DevTools Protocol and is available in Chrome/Edge only.

API Calls #

ApiCall(url) performs one HTTP request as a step — handy for setting up or checking backend state. Only the URL is required; chain methods to configure the rest.

import { ApiCall } from '@tomationjs/dsl'

ApiCall('https://api.example.com/users')
  .method('POST')
  .headers({ Authorization: 'Bearer {{ctx.token}}' })
  .jsonBody({ name: 'Ana', email: '{{data.user.email}}' })
  .status(201)
  .timeout(5000)
  .secret('password')
  .save('userId', 'data.id')
  .saveStatus('createStatus')
  .inPage()
Argument / methodTypeRequiredDescription
ApiCall(url)stringRequiredRequest URL. Must be non-empty.
.method(m)'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'OptionalHTTP method, uppercase and case-sensitive. Defaults to 'GET'.
.headers(h)Record<string, string>OptionalRequest headers.
.jsonBody(b)JSON object or arrayOptionalJSON body. Sends Content-Type: application/json unless a Content-Type header is set. Not allowed with GET or with .rawBody.
.rawBody(s)stringOptionalRaw body string. Not allowed with GET or with .jsonBody.
.status(s)number | '1xx'..'5xx' | { min, max } | Array<number | 'Nxx'>OptionalExpected status. Codes are 100–599; a list holds 1–20 entries.
.timeout(ms)numberOptionalInteger 1–600000 ms. Defaults to 30000.
.secret(...names)string[]OptionalExtra header and JSON field names to mask (see Secret masking).
.save(key, jsonPath?)string, string?OptionalSave the response body, or the value at jsonPath in a JSON body, to {{ctx.key}}. Values over 1,048,576 characters are truncated.
.saveStatus(key)stringOptionalSave the status code as a decimal string to {{ctx.key}}.
.inPage()noneOptionalSend the request from the page instead of the background.

{{data.*}}, {{ctx.*}} and {{paramName}} tokens are resolved in the URL, header values and body (string values at any depth; object keys are not resolved).

Background vs. page context

By default the request runs in the Background_Context: the extension's background worker sends it. It is not a page request, so AssertRequest cannot see it. With .inPage() the request runs in the Page_Context: the content script sends it inside the page, so the page's cookies, session and CORS rules apply. These are ordinary page requests, so AssertRequest can see them.

Success and failure

Success: with no .status(...), the response status must be 200–299. With .status(...), the step passes only if the status matches it; the 200–299 default is not applied.

Failure: a status mismatch, a network failure, a timeout (default 30000 ms), an unresolved token ({{ctx.*}}, {{data.*}} or task parameter), or a save failure (.save(key, jsonPath) with a body that is not valid JSON or a path that does not exist; the context key is left unchanged). A failed step follows the usual retry/skip/halt handling.

Secret masking

Secret values are replaced with *** in LOG messages, STEP_STARTING messages and persisted run records. The real values are still sent in the request. Headers masked by default (case-insensitive) are Authorization, Proxy-Authorization, Cookie, Set-Cookie, X-API-Key and X-Auth-Token, plus every name passed to .secret(...). JSON body fields whose name equals a .secret(...) name are masked at any depth, matched by exact case.

Network Usage in the Run Log #

While a test runs, the requests the page makes are captured and shown inline in the run log, interleaved with the steps in the order they were initiated. Each captured request appears as its own entry directly beneath the step that was executing when it fired, so you can see exactly which action triggered which call.

Per-step summary

Under each step, a small network glyph with a count badge shows how many requests were attributed to it. While the step is running and the count is not yet known, a subtle pulsing dot indicates capture is in progress. Steps that made no requests show nothing.

Request entry

A captured request entry shows, on one line: a network glyph (so it is never mistaken for a step), the HTTP method, the URL, and the response status. When the request host matches the page's host, the origin is collapsed to […] so the endpoint path is easy to scan — the full URL is available on hover. A status shown in an amber/pending style means the response has not completed (or failed to capture) yet.

Expanded detail

Click a request entry to expand it. The detail view shows the full untruncated URL, the query parameters, and the request and response bodies. Values are shown verbatim. When a body was shortened while capturing (to keep captures lightweight), it is labeled (truncated at capture); when a response body could not be captured, the entry notes that it is unavailable.

Relationship to AssertRequest

The requests displayed here are the same captured set that AssertRequest evaluates against. An AssertRequest step reads as a sentence in the log — for example, Assert Request GET "[…]/posts?userId=1" has been done with status 200 — so you can cross-reference the assertion against the actual requests captured on the preceding steps.

Tests #

Tests are declared using the Test(name, callback) function in *.test.ts files. Each test has a descriptive name and a callback containing the sequence of interactions and assertions that make up the test scenario.

Test File Structure

Test files live in the directory specified by the tests field in your tomation.config.ts. Each file imports the Test function from the DSL along with any interaction or assertion functions needed, and imports POM elements to interact with.

// tests/login.test.ts
import { Test, Click, AssertExists, AssertHasText } from '@tomationjs/dsl'
import Login from '~/pom/login.pom'

Test('Login with valid credentials', () => {
  Login.fillCredentials({ username: 'admin', password: 'secret' })
  Login.submit()
  AssertHasText(Login.message, 'Login successful')
})

Test('Login shows error on empty submit', () => {
  Click(Login.submitButton)
  AssertHasText(Login.errorMessage, 'required')
})

Compilation & Execution

When you run npx tomation compile, the compiler processes all *.test.ts files in the configured tests directory, resolves POM imports, and includes the compiled tests in the .tomation.json output file.

Tests are run interactively via the Tomation browser extension. Load the compiled .tomation.json file in the extension panel, select one or more tests, and execute them against the live page. The extension renders real-time results including pass/fail status and step-by-step logs.

Display Labels

Tests and automations are displayed in the extension using the format sourceFile: label. The sourceFile is the relative path from the project root with the tests/ or automations/ prefix removed and file extensions stripped. For example, login: Login with valid credentials or auth/login: Login with valid credentials for tests in subfolders.

Automations #

Automations are like Tests but with typed parameters that are filled in at runtime via a form in the browser extension. Instead of hardcoding values, you declare a params object with typed fields — the extension generates a form for each parameter, letting you reuse the same procedure with different inputs each time.

Declaration

Declare automations using the Automation(name, callback) function in *.automation.ts files. The callback receives a typed params object whose shape determines the form controls shown in the extension.

// automations/todo.automation.ts
import { Automation, AssertExists, AssertHasText, SaveText } from '@tomationjs/dsl'
import Todo from '~/pom/todo.pom'

Automation('Add Todo Item', (params: { item: string }) => {
  Todo.addItem({ text: params.item })
  AssertExists(Todo.firstItem)
  SaveText(Todo.firstItemText).as('savedItem')
  AssertHasText(Todo.firstItemText, params.item)
})

Parameter Types

The TypeScript type of each parameter field controls which form input is rendered in the extension panel:

TypeForm InputNotes
stringText inputFree-text field
numberNumber inputCoerced to parseFloat
DateDate pickerSent as ISO YYYY-MM-DD
'a' | 'b' | 'c'Select dropdownConstrained options

Optional parameters use ? in the type definition and won't block execution if left empty in the form.

Configuration

Automation files live in the directory specified by the automations field in your tomation.config.ts. Ensure the field is set so the compiler includes your automation files in the output:

// tomation.config.ts
export default {
  meta: { name: 'My App', urls: ['http://localhost:3000'] },
  pom: './pom',
  tests: './tests',
  automations: './automations',
  baseUrl: './',
}

Differences from Tests

TestsAutomations
ValuesHardcodedProvided at run-time via form
File suffix.test.ts.automation.ts
DeclarationTest('name', fn)Automation('name', fn)
ParametersNoneTyped params object
Use caseRegression checksReusable user-driven procedures

POM Files #

Tomation uses the Page Object Model (POM) pattern to organize element locators and reusable tasks into dedicated files. Each page or section of your application gets its own *.pom.ts file that declares elements, reusable tasks, and exports them as a single default object.

Folder-Based Namespacing

Organize POM files in folders to avoid naming conflicts. Subfolders create namespaces when imported — for example, import Login from '~/pom/login.pom' imports the default export from that POM file. As your project grows, use folders to group related pages (e.g., pom/auth/login.pom.ts, pom/auth/signup.pom.ts).

The Export Default Pattern

Each POM file exports a default object containing all its declared elements and tasks. This makes imports clean and gives consuming test files a single namespace to work with.

// pom/login.pom.ts
import { is, idIs, Task, Type, TypePassword, Click } from '@tomationjs/dsl'

const usernameInput = is.INPUT.where(idIs('username')).as('Username')
const passwordInput = is.INPUT.where(idIs('password')).as('Password')
const submitButton = is.BUTTON.where(idIs('login-btn')).as('Submit')
const message = is.DIV.where(idIs('message')).as('Message')

const fillCredentials = Task((params) => {
  const { username, password } = params
  Type(username).in(usernameInput)
  TypePassword(password).in(passwordInput)
}).as('Fill Credentials')

const submit = Task(() => {
  Click(submitButton)
}).as('Submit')

export default { usernameInput, passwordInput, submitButton, message, fillCredentials, submit }

Tests and automations can then import the POM and use its elements and tasks directly:

import Login from '~/pom/login.pom'

// Use elements
Click(Login.submitButton)

// Use tasks
Login.fillCredentials({ username: 'admin', password: 'secret' })
Login.submit()

Generate POM Files with the Lab

Instead of writing POM files by hand, you can use the Lab tab in the Tomation extension to generate them automatically using AI. The Lab lets you visually inspect page elements and produces complete .pom.ts files — including element declarations and reusable Task functions.

How it works:

  1. Configure your AI provider — Set up your API key (OpenAI, Anthropic, Gemini, or a custom endpoint) in the Lab's AI Configuration section.
  2. Choose a context mode — Select "Full HTML" to send the entire page, or "Inspect Element" to pick specific components.
  3. Select elements — In Inspect Element mode, click on page elements to build a multi-node selection (up to 20 nodes). Each selected element is shown in a mini-editor where you can review its HTML.
  4. Review and edit — The Code Viewer shows the HTML that will be sent to AI. You can edit it directly before generating.
  5. Generate — Click "Generate POM" and the AI produces a complete .pom.ts file with element locators and Task functions for common user workflows.

Privacy: Email addresses, passwords, and personally identifiable information are automatically stripped from the HTML before sending to any AI service.

Tip: The Lab generates production-ready POM files using the same DSL functions documented above (is, Task, where matchers). You can use the generated output as-is or refine it to match your project's naming conventions.

Component Object Model #

A Component models a reusable UI widget that appears many times on a page — a searchable select, a date picker, a row of action buttons. Where a POM describes a fixed page or section, a Component is defined once and then instantiated against a different root element each time it appears. Its locators resolve relative to that root, so two instances on the same page never collide.

Defining a Component

Declare a Component in a dedicated *.com.ts file with the Component(({ el }) => { ... }) factory. The factory receives a single destructured el — a root placeholder that stands in for the concrete root element each instance will bind at runtime. Inside, you declare the component's locators and expose Task-like actions, then return them as a single object.

// components/search-select.com.ts
import {
  Component, Task, Type, Click, AssertExists, is,
  classIncludes, placeholderIs, isNthElement,
} from '@tomationjs/dsl'

const SearchSelect = Component(({ el }) => {
  const trigger = is.BUTTON.where(classIncludes('select-trigger')).childOf(el).as('Open Select')
  const searchBox = is.INPUT.where(placeholderIs('Search...')).childOf(el).as('Search Field')
  // Portal-rendered dropdown list: document-scoped (no .childOf(el)).
  const firstResult = is.LI.where(isNthElement(1)).as('First Result')

  const choose = Task((params: { query: string }) => {
    Click(trigger)
    Type(params.query).in(searchBox)
    Click(firstResult)
    AssertExists(trigger)
  }).as('Choose Option')

  return { trigger, searchBox, firstResult, choose }
})

export default SearchSelect

Per-Locator Root Scoping with childOf(el)

Each locator decides for itself whether it is root-scoped. Chain .childOf(el) against the placeholder to restrict the search to the instance's root subtree — this is what lets the same Component appear many times without its locators matching another instance's elements. A locator that does not chain .childOf(el) stays document-scoped, which is exactly what you want for a portal or overlay that the widget renders outside its own subtree (a dropdown list appended to <body>, for example).

Component Actions

Actions are declared with the same Task(...) builder used in POM files, so they support the same steps — Click, Type, Select, assertions, and so on. An action operates over the component's own locators, so it automatically respects each locator's scoping. In the example above, choose opens the select, types a query, picks the first result, and asserts the trigger is still present.

Instantiating with .in(root)

Bind a Component to a concrete root element with .in(root), where root is any element locator. Each call returns an independent instance, so the same Component can be placed on several fields of one page and its root-scoped locators will never collide. Invoke an action on the instance just like a POM task, passing {{data.*}} tokens (or {{ctx.*}}) exactly as you would for a task.

// tests/search-select.test.ts
import { Test } from '@tomationjs/dsl'
import user from '~/data/user.data'
import SearchForm from '~/pom/search-form.pom'
import SearchSelect from '~/components/search-select.com'

const country = SearchSelect.in(SearchForm.countryField)
const city = SearchSelect.in(SearchForm.cityField)

Test('Pick country and city via the searchable select', () => {
  country.choose({ query: user.address })
  city.choose({ query: 'Springfield' })
})

Here country and city are two instances of the same Component bound to two different form fields. Each choose call resolves its root-scoped locators within its own field, and the {{data.*}} token (user.address) passes through just like a task parameter.

Configuration

Component files live in the directory named by the components field of your tomation.config.ts, alongside pom, tests, automations, and data. The field is optional — when it is absent, projects compile exactly as before.

// tomation.config.ts
export default {
  meta: { name: 'My App', urls: ['http://localhost:3000'] },
  pom: './pom',
  tests: './tests',
  automations: './automations',
  data: './data',
  components: './components',
  baseUrl: './',
}

Component Groups in the Run Log

To keep the log readable when a component action expands into several steps, each component action renders as a collapsed group by default — in both the Test Plan preview and the live Run Log. You can expand any group to see its individual steps, and collapse it again. Plain POM tasks are unaffected and render exactly as they do today.

While a collapsed group is running, its header shows the current step underneath so you can follow progress without expanding it. The behavior keyed off run state:

StateCollapsed group display
RunningHeader plus the current step line
SuccessHeader only, marked passed
FailureAuto-expands down to the failing step

On failure the group opens automatically to the step that failed (for nested components, the whole enclosing chain expands), so you always land on the problem without hunting for it.