# toets > Cross-platform E2E testing for TV apps: one test for web, Android TV / Fire TV and tvOS, with focus and the remote as first-class primitives. # Install and first test Source: https://yusufyildirim.github.io/toets/getting-started/index.md toets is a set of [Playwright Test](https://playwright.dev/docs/intro) fixtures for TV apps. Every platform is a Playwright project, and every test receives one fixture, `app`: the app under test on the current platform. You keep Playwright's runner, reporters, UI mode, retries and sharding. ::: warning Pre-alpha toets APIs may change between minor versions until 1.0. ::: ## Requirements | Platform | Host | Needs | | -------------------- | ------------------------ | ------------------------------------------- | | Web | any | Chromium, installed through Playwright | | Android TV / Fire TV | macOS, or Linux with KVM | Android SDK with an Android TV system image | | tvOS | macOS | Xcode with a tvOS simulator runtime | Node 24 or later. toets starts Appium and boots, resets and shuts down emulators and simulators itself; see the [platform pages](/platforms/web). ## 1. Install ```sh npm install --save-dev @toets/test @playwright/test # one driver per platform you target npm install --save-dev @toets/driver-web @toets/driver-android-tv @toets/driver-tvos npx playwright install chromium ``` Drivers load when a project first needs them, so install only the platforms you test. ## 2. Configure `playwright.config.ts`: ```ts import { defineConfig, platforms } from '@toets/test'; export default defineConfig({ testDir: './e2e', webServer: { command: 'npm run serve', url: 'http://localhost:8080' }, app: { web: { url: 'http://localhost:8080' }, androidTV: { apk: './build/app-debug.apk', package: 'com.example.tv' }, tvOS: { app: './build/Example.app', bundleId: 'com.example.tv' }, }, projects: [ platforms.web(), platforms.androidTV({ model: 'tv_1080p', osVersion: '34' }), platforms.tvOS({ osVersion: '18' }), ], }); ``` - `app` says how to start the app on each platform; `projects` says where tests run. Drop the platforms you do not target. - toets does not serve or build the app. `webServer` (Playwright's option) serves the web build; the APK and `.app` come from your build. - Project names are the platform names: `web`, `android-tv`, `tvos`. - App-specific flows (sign-in, waiting for your splash screen) belong in your own fixtures, not here: see [Writing tests](/guides/writing-tests). Every option: [`@toets/test` config](/reference/test/docs/config). ## 3. Give elements test IDs toets finds elements by test ID or text. The test ID is `data-testid` on web, the resource ID on Android and the accessibility identifier on tvOS; React Native's `testID` sets all three. Elements also need to be focusable the way the platform expects (on web: a focusable element or `tabindex`). See [Locators and assertions](/concepts/locators-and-assertions). ## 4. Write a test `e2e/home.spec.ts`: ```ts run import { test, expect, Key } from '@toets/test'; test('opens details from the first rail', async ({ app }) => { await app.launch(); const card = app.getByTestId('rail-0-card-2'); await app.focus.pressUntilFocused(Key.RIGHT, card); await expect(card).toBeFocused(); await app.remote.press(Key.SELECT); await expect(app.getByTestId('details-screen')).toBeVisible(); }); ``` There is no click. `pressUntilFocused` presses `RIGHT` until the card holds focus, checking where focus landed after every press; then `SELECT` activates it. See [Focus](/concepts/focus). ## 5. Run ```sh npx playwright test --project=web # fastest loop npx playwright test # every platform npx playwright show-report # steps, failure dumps, logs ``` A run ends with the parity summary; the full matrix (which test ran on which platform, and why any was skipped) is in `toets-report/parity.md`: ```text 1 passed (1.3s) toets parity (1 tests): web: 1 passed Parity matrix: toets-report/parity.md ``` A failure prints the error with a `Hint:` and a `Docs:` page, and attaches a failure dump. See [Debugging failures](/guides/debugging-failures). ## Next - [Concepts](/concepts/locators-and-assertions): the few ideas toets is built on. - [Working with agents](/getting-started/agents): skills, an `AGENTS.md` template and docs for coding agents. - [CI recipes](/ci/). --- # Working with agents Source: https://yusufyildirim.github.io/toets/getting-started/agents.md Most toets tests are written and maintained by coding agents, so toets ships its knowledge in forms agents load cheaply. An agent with no prior context should be able to set up toets, write a correct cross-platform test and debug a failure from these alone. | Artifact | Where | Use | | ------------ | ---------------------------------------------------- | ------------------------------------------------------- | | Skills | `skills/` in the toets repository | Task-level guidance, loaded when the task matches | | `AGENTS.md` | Your project root (template below) | Project rules every agent session sees | | Offline docs | `node_modules/@toets/*/docs/` | Version-matched pages, no network needed | | `llms.txt` | Docs site root, with `llms-full.txt` | Index of every page, and every page in one file | | Errors | Test output | Each error has a code, a hint and a docs link | | Error codes | [Error code index](/reference/core/docs/errors) | Every `ToetsError` code, generated from the sources | | MCP server | [`@toets/mcp`](/reference/mcp) | Explore a running app with the same primitives as tests | ## Skills Four skills in the [open agent skills format](https://agentskills.io), each short and linking to pages here instead of repeating them: | Skill | Triggers when the agent | | ---------------------- | ---------------------------------------------------------- | | `toets-setup` | adds toets to a project, adds a platform or sets up CI | | `toets-write-tests` | writes or changes toets tests or page objects | | `toets-debug-failures` | investigates a failing or flaky toets test | | `toets-migrate` | ports tests from Playwright, Appium / WebdriverIO or Detox | Install all of them into your project with the [skills CLI](https://github.com/vercel-labs/skills), which detects the agents you use: ```sh npx skills add yusufyildirim/toets npx skills add yusufyildirim/toets --skill toets-write-tests # just one ``` Or copy `skills//` from the repository into your agent's skills folder (for example `.claude/skills/` or `.agents/skills/`). Skills refer to docs pages by slug, such as `concepts/focus`: the page at `/concepts/focus` on this site. ## `AGENTS.md` template Drop this into your project's `AGENTS.md` (or merge it into the one you have) and fill in the comment: ````md # E2E tests (toets) TV end-to-end tests live in `e2e/` and run with toets on Playwright Test. - Fast loop: `npx playwright test --project=web` - All platforms: `npx playwright test` - Report: `npx playwright show-report` ## Rules - No click. Move focus with `app.focus.pressUntilFocused(Key.X, locator)` (or `navigateTo`, `app.remote.press`), assert `toBeFocused()`, then press `Key.SELECT`. - Locate by test ID (`app.getByTestId`). Add a missing test ID to the app instead of matching layout or volatile text. - Never sleep or poll by hand: assertions retry. Anchor a negative assertion on a positive one first. - Platform gaps are capabilities: `test(name, requires('key.color'), fn)`, never `if (platform === ...)`. - Page objects live in `e2e/pages/`, take `app`, expose locators and actions, and do not assert beyond waiting until loaded. - Data-dependent tests mock the network with `app.network.use(...)` before `app.launch()`. - When a test fails, read the error's `Hint:`, its `Docs:` page and the failure dump before changing the test. Skipped platforms and their reasons are in `toets-report/parity.md`. ## Docs Installed toets packages ship version-matched docs in `node_modules/@toets/*/docs/`; every error code is in `node_modules/@toets/core/docs/errors.md`. The docs site has the same pages plus `llms.txt` and `llms-full.txt`. The toets agent skills cover setup, writing tests, debugging failures and migrating. ```` ## Docs for agents - Prefer the offline copy in `node_modules`: it matches the installed version. - [`llms.txt`](/llms.txt) indexes every page with a one-line summary; [`llms-full.txt`](/llms-full.txt) is the whole site in one file. Every page is also served as markdown: append `.md` to its URL. - Errors are docs too. A failing test prints `ToetsError: [CODE] what happened`, the likely cause and fix (`Hint:`) and the page to read (`Docs:`, with its offline path in `node_modules`). Agents should act on those before guessing; the [error code index](/reference/core/docs/errors) lists every code. --- # Locators and assertions Source: https://yusufyildirim.github.io/toets/concepts/locators-and-assertions.md A **locator** describes how to find elements; it holds no element. It resolves again on every use, so it never goes stale when the screen re-renders. An **assertion** (`expect(locator).toX()`) retries until it passes or times out. Together they replace finding, waiting and checking by hand. ```ts run import { test, expect, Key } from '@toets/test'; test('saves a title to the watchlist', async ({ app }) => { await app.launch(); const rail = app.getByTestId('rail-popular'); const card = rail.getByTestId('card').nth(2); await app.focus.pressUntilFocused(Key.DOWN, rail); await app.focus.pressUntilFocused(Key.RIGHT, card); await app.remote.press(Key.SELECT); await expect(app.getByText('Added to watchlist')).toBeVisible(); await expect(app.getByTestId('watchlist-count')).toHaveText('1'); }); ``` ## Selectors v1 has two selectors, chainable from `app` or from another locator (each step searches inside the previous matches): - `getByTestId(id)`: preferred. Stable across layouts, languages and platforms. - `getByText(text, { exact })`: for user-visible copy. Substring and case-insensitive unless `exact: true`; a `RegExp` also works. Narrow multiple matches with `first()` and `nth(index)`, in tree order. Actions and single-element reads are strict: a locator that matches several elements fails instead of picking one. Role and label selectors come later. How a test ID maps to each platform: | Platform | Test ID source | | -------------------- | ----------------------------------- | | Web | `data-testid` attribute | | Android TV / Fire TV | view resource ID | | tvOS | `accessibilityIdentifier` | | React Native | `testID` (maps to all of the above) | ## Matchers Matchers are implemented once in the core, over the same element snapshot on every platform, so `toBeFocused()` means the same on web, Android TV and tvOS. Element matchers: `toBeVisible`, `toBeInViewport`, `toBeFocused`, `toHaveFocusWithin`, `toBeEnabled`, `toBeDisabled`, `toBeSelected`, `toBeBusy`, `toHaveText`, `toContainText`, `toHaveCount`. The app, `app.media` and `app.network` have their own (text snapshots, screenshots, playback, requests). Every matcher takes `{ timeout }` (default: Playwright's `expect.timeout`, 5 s); element matchers support `.not`. Semantics of each, including how missing elements count: [assertions reference](/reference/core/docs/assertions). Selector details: [locators reference](/reference/core/docs/locators). ## Traps - **Read values only through matchers.** `expect(await locator.text()).toBe('1')` reads once and does not retry; `await expect(locator).toHaveText('1')` does. - **No click, no tap, no fill.** On TV, input is the remote. Locators are for finding and asserting; actions go through [focus](/concepts/focus) and the [remote](/concepts/remote-and-keys). - **Visible is not focusable.** An element can be visible yet unreachable by the remote. Assert focus when the user would navigate to it. - **Test IDs are part of the app's contract.** Add one where a test needs it instead of matching layout positions or translated copy. --- # Focus Source: https://yusufyildirim.github.io/toets/concepts/focus.md On TV, exactly one element holds **focus** and the remote moves it. Focus is what the user sees as "where I am", so it is what toets tests act through and assert on. There is no pointer: to activate something, focus it, then press `SELECT`. The app's focus engine decides where every press goes. Focus guides, focus memory, custom resolvers and JS focus engines keep that logic in app code, so no description of it from outside is ever complete. toets does not try: it presses a direction, reads where focus landed, and repeats until the target holds focus. ```ts run import { test, expect, Key } from '@toets/test'; test('remembers the focused card when returning to a rail', async ({ app }) => { await app.launch(); const card = app.getByTestId('rail-0-card-3'); await app.focus.pressUntilFocused(Key.RIGHT, card); await expect(card).toBeFocused(); await app.remote.press(Key.DOWN); await expect(app.getByTestId('rail-1')).toHaveFocusWithin(); await app.remote.press(Key.UP); await expect(card).toBeFocused(); }); ``` ## API - `app.focus.pressUntilFocused(key, target)` presses one D-pad direction until the target (or an element inside it) holds focus, reading focus after every press, and returns the number of presses. The target may not exist yet: virtualized lists render items as focus approaches. It fails fast with `FOCUS_STUCK` when a press does not move focus, `FOCUS_LOOP` when focus comes back to an element it left, and `FOCUS_UNREACHABLE` after `maxPresses` (default 50). **The recommended way to move focus.** - `app.focus.navigateTo(target)` moves focus when the way there is more than one direction. It aims each press by element geometry, checks focus after it the same way, and detours around presses that did not move focus. The target must be on screen. - `app.focus.current()` is a locator for the focused element. - `app.focus.waitForChange(action)` runs `action` and waits until focus moves to another element. - `toBeFocused()` and `toHaveFocusWithin()` assert focus on an element or inside a container. Both movers are one step in the report, with every press inside it. How they decide and fail: [focus navigation reference](/reference/core/docs/focus-navigation). ## When to use which - **Getting somewhere** is not what the test is about: `pressUntilFocused`, one call per direction (`DOWN` to the rail, then `RIGHT` to the card). It survives layout changes that break a fixed key sequence, and its errors say exactly where focus went. Use `navigateTo` when the route is not worth spelling out. - **Navigation is the behavior under test** (focus memory, wrap-around, traps, back behavior): press keys explicitly and assert focus after each press. ## Where focus comes from - **The platform's focus engine** (tvOS, Android TV, DOM focus on web) owns focus: toets reads it black-box, with no app changes. - **A JS focus engine** (Norigin Spatial Navigation, LRUD, react-tv-space-navigation, ...) keeps focus in app state, invisible from outside. The app reports it through the [SDK](/concepts/sdk) with `reportFocus()`: [reporting focus](/reference/sdk/docs/focus). ## Traps - **Assert focus after moving.** A press that lands on the wrong element fails much later, somewhere confusing. `await expect(target).toBeFocused()` right after makes the failure point at the cause. - **Focus is not visibility.** A visible element may be disabled or unreachable from the current position. If a user must reach it, test that they can. - **The app's focus engine decides.** tvOS, Android and web each have their own rules for "nearest in this direction", and apps add more. toets sends the press and observes the result; assertions on focus are portable, assumptions about exact paths are not. - **Wrap-around rows and menus.** Pressing toward a target that is not in that direction cycles forever on a user's remote; `pressUntilFocused` stops at the first repeat with `FOCUS_LOOP`. - **JS focus engines need the SDK.** Without `reportFocus()`, toets sees DOM or native focus, usually nothing, and every focus assertion fails. --- # Remote and keys Source: https://yusufyildirim.github.io/toets/concepts/remote-and-keys.md Tests press **semantic keys** (`Key.SELECT`, `Key.PLAY_PAUSE`), never platform keycodes. Each driver maps a key to real input on its platform: an Android keycode, an Apple TV remote button, a browser keyboard event. Input is always real platform input, never an event injected into the app, so the app's own focus engine and key handling are what get tested. ```ts run import { test, expect, Key } from '@toets/test'; test('toggles playback from the remote', async ({ app }) => { await app.launch(); await app.focus.navigateTo(app.getByTestId('play-button')); await app.remote.press(Key.SELECT); await expect(app.media).toBePlaying(); await app.remote.press(Key.PLAY_PAUSE); await expect(app.media).toBePaused(); }); ``` ## API - `press(key)`: one press. `press(key, { holdMs })` holds it (`key.longpress`). - `longPress(key, holdMs?)`: the same, default hold 1000 ms. - `repeat(key, times, { intervalMs })`: the same key several times. - `sequence(keys, { intervalMs })`: several keys in order. Each press is a step in the report and is listed under "last keys" in failure dumps. ## Keys and capabilities D-pad (`UP`, `DOWN`, `LEFT`, `RIGHT`) and `SELECT` exist everywhere. Every other key needs a [capability](/concepts/capabilities): | Keys | Capability | | -------------------------------- | ---------------------------------------------- | | `BACK`, `HOME`, `MENU`, `INFO` | `key.back`, `key.home`, `key.menu`, `key.info` | | `PLAY_PAUSE` | `key.media.toggle` | | `PLAY`, `PAUSE`, `STOP` | `key.media.discrete` | | `FAST_FORWARD`, `REWIND` | `key.media.seek` | | `NEXT`, `PREVIOUS` | `key.media.track` | | `RED`, `GREEN`, `YELLOW`, `BLUE` | `key.color` | | `DIGIT_0` ... `DIGIT_9` | `key.numeric` | | `CHANNEL_UP`, `CHANNEL_DOWN` | `key.channel` | Pressing a key the platform lacks throws `KEY_UNSUPPORTED`, naming the capability. Tests that need such a key declare it with `requires` and are skipped, with a reason, where it is missing. Which keys each platform has: [web](/reference/driver-web/docs/keys), [Android TV](/reference/driver-android-tv/docs/keys), [tvOS](/reference/driver-tvos/docs/remote). ## Overrides Some apps define their own gesture for a key the remote lacks, for example "hold right to fast-forward" on Apple TV. Declare it once in the project's `toets.keyOverrides` instead of branching in tests; overridden presses are flagged in the step title and the parity matrix. ```ts import { defineConfig, platforms, Key } from '@toets/test'; export default defineConfig({ app: { tvOS: { app: './build/Example.app', bundleId: 'com.example.tv' } }, projects: [ platforms.tvOS({ toets: { keyOverrides: { FAST_FORWARD: { as: Key.RIGHT, holdMs: 800 } } }, }), ], }); ``` ## Traps - **`PLAY`, `PAUSE` and `PLAY_PAUSE` are different keys.** Most remotes only have the toggle. Use `PLAY_PAUSE` unless the test is about discrete play or pause. - **`BACK` is the Menu button on Apple TV.** The driver maps it; tests stay semantic. - **Fixed key sequences are brittle.** `repeat(Key.RIGHT, 7)` encodes today's layout. Use [`pressUntilFocused`](/concepts/focus) unless the sequence itself is under test. - **Do not add sleeps between presses.** `repeat` and `sequence` already space presses (`intervalMs`, default 100 ms, configurable as `toets.remote.intervalMs`). Between separate presses, assert the state you expect instead of waiting. - **Assert focus after a screen change.** After a key that opens or closes a screen, assert focus on the new screen (`toBeFocused`) before the next press, not just that it is visible. tvOS drops presses until the new screen holds focus ([tvOS](/platforms/tvos)). `pressUntilFocused` and `navigateTo` wait for focus themselves. --- # Capabilities and parity Source: https://yusufyildirim.github.io/toets/concepts/capabilities.md toets's promise is that a test means the same thing on every platform. Where a platform can not do something, it says so through a **capability** instead of approximating it. Tests declare the capabilities they need; on platforms without them the test is **skipped with a reason**, never silently changed. ```ts run import { test, expect, Key, requires } from '@toets/test'; test('the red key opens the guide', requires('key.color'), async ({ app }) => { await app.launch(); await app.remote.press(Key.RED); await expect(app.getByTestId('guide')).toBeVisible(); }); ``` ## Where capabilities come from A target's capabilities are the union of its **driver's** (what the platform and its automation can do) and those granted by the [in-app SDK](/concepts/sdk) when connected (`tree.hierarchy`, `sync.idle`, `media.state`, `app.state`, `logs`). | Capability | Means | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `key.*` | the remote has the key, see [Remote and keys](/concepts/remote-and-keys) | | `key.longpress` | keys can be held | | `tree.hierarchy` | the tree nests like the app's views (a whole-screen [text snapshot](/concepts/text-snapshots) has the same shape everywhere) | | `text.input` | system text fields take text: `fill` and `app.keyboard` on them, see [Text input](/concepts/text-input) | | `deeplink.launch` | `app.launch({ deepLink })` starts the app from a link, see [Deep links](/concepts/deep-links) | | `deeplink.open` | `app.openDeepLink(url)` delivers a link to the running app | | `sync.idle` | the app reports when it is idle, see [Idle](/concepts/idle) | | `media.state` | player state can be read: `expect(app.media)` | | `app.state` | `app.launch({ state })` can start in a named state | | `network.mock` | [network mocking](/concepts/network-mocking) is available | | `screenshot.element` | screenshots of a single element | | `platform.events` | `app.platform.emit('suspend' \| 'resume' \| 'network-lost' \| 'network-restored')`; a lost network is restored after each test | | `logs`, `video` | device logs and screen recording are attached to results | Each platform's set: [web](/reference/driver-web/docs/capabilities), [Android TV](/reference/driver-android-tv/docs/capabilities), [tvOS](/reference/driver-tvos/docs/capabilities). For `requires`, SDK capabilities count as present when `toets.sdk` is on (the app only connects at launch), and `network.mock` when `toets.mock` is on. `requires(...)` also works on a `test.describe` (`test.describe('guide', requires('key.color'), () => ...)`) and merges with other details: `{ ...requires('media.state'), tag: '@smoke' }`. Reference: [`requires`](/reference/test/docs/requires). ## Parity matrix Every run writes `toets-report/parity.md`: which test ran on which platform, and why each skip happened. A gap is visible, not a silent difference. See [reporting](/reference/test/docs/reporting). ## Traps - **Do not branch on the platform.** `if (app.platform.name === 'tvos')` hides a gap inside a passing test. Declare `requires`, or split the test. - **`app.platform.has(capability)`** exists for page objects and fixtures that adapt how they do something, not for tests deciding whether to check it. - **The escape hatch is a last resort.** `app.platformOnly(platform, handle => ...)` runs code against the underlying tool (Playwright `Page`, WebdriverIO browser) on one platform and is a no-op elsewhere. It is marked in reports and flagged by the ESLint plugin. Prefer asking for a capability. --- # Idle and synchronization Source: https://yusufyildirim.github.io/toets/concepts/idle.md Every toets assertion **retries until it passes or times out**. That alone makes tests correct without sleeps. When the [in-app SDK](/concepts/sdk) is enabled (`toets: { sdk: true }`) and connected (`sync.idle`), toets additionally knows when the app is **idle**, and evaluates checks at moments where the screen is settled. The app is idle when it has had no tracked work for about 100 ms. Tracked work: network requests, animations, short timers (under about 1.5 s), focus and navigation transitions, and anything the app marks busy itself. ```ts run import { test, expect, Key } from '@toets/test'; test('closing the menu leaves no overlay behind', async ({ app }) => { await app.launch(); await app.remote.press(Key.LEFT); await expect(app.getByTestId('side-menu')).toHaveFocusWithin(); await app.remote.press(Key.RIGHT); await expect(app.getByTestId('home-screen')).toHaveFocusWithin(); await expect(app.getByTestId('side-menu')).not.toBeVisible(); }); ``` ## What idle changes | Without idle | With idle | | ---------------------------------------------- | --------------------------------------------------- | | assertions poll until they pass | assertions check when the app settles, then poll | | `.not` passes as soon as the element is absent | `.not` passes once the app is idle and it is absent | | a timeout says what was expected | a timeout also names what kept the app busy | ## Never a gate Idle only speeds things up. A video player, a clock or a polling request can keep an app busy forever; after `toets.idle.budgetMs` (default 2000) toets falls back to polling and names the busy resource in the failure message. Exclude known noise with the SDK's `idle.ignore`, and mark work the SDK cannot see with `markBusy()`: [idle tracking](/reference/sdk/docs/idle). Host-side options: [idle sync](/reference/core/docs/idle). ## Traps - **Negative assertions pass too early.** Without idle, `not.toBeVisible()` passes before the element had a chance to appear. Anchor it on a positive assertion that proves the screen reached the state you mean, as in the example. - **Never sleep.** A fixed wait is either too short on a slow emulator or wasted time everywhere else. If you need to wait for something, assert it. - **Raising timeouts hides busy apps.** When an assertion times out with a busy resource named, the fix is usually in the app or the SDK noise configuration, not in the timeout. --- # Network mocking Source: https://yusufyildirim.github.io/toets/concepts/network-mocking.md Tests that depend on data mock it. toets runs [MSW](https://mswjs.io) handlers in a **mock server on the test host**. The app sends its API traffic to that server; matched requests get the handler's response, unmatched ones are proxied to the real backend. Because it is plain HTTP on the host, it works the same on web, emulators and simulators, without certificates. Turn it on in the config with `toets: { mock: true }` (the `network.mock` capability): ```ts run import { test, expect, http, HttpResponse } from '@toets/test'; test('shows an empty state without favorites', async ({ app }) => { app.network.use(http.get('*/api/favorites', () => HttpResponse.json([]))); await app.launch(); await expect(app.getByTestId('favorites-empty')).toBeVisible(); await expect(app.network).toHaveRequested({ method: 'GET', url: /\/api\/favorites$/ }); }); ``` ## How it works 1. Each worker starts a mock server. Its URL reaches the app in the launch payload (`mockUrl`), through the platform's launch channel: a URL parameter on web, an intent extra on Android, launch arguments on tvOS. 2. The app, when it finds `mockUrl`, sends API requests there with the real origin in the `x-toets-original-origin` header. This is the one cooperation mocking needs from the app: [app integration](/reference/mock/docs/app-integration) shows it for fetch and axios. 3. The mock server rebuilds the request as the app meant it (real origin plus path), so handlers match exactly what the real API would see. 4. Handlers added with `app.network.use()` apply to the current test only and reset after it. The most recently added handler wins. 5. Baseline handlers from the config apply to every test, under the per-test ones: `toets: { mock: { handlers: [...] } }`. `onUnhandledRequest: 'reject'` fails unmatched requests (`MOCK_UNHANDLED`) instead of proxying them, for a hermetic suite. 6. `app.network.requests()` and `expect(app.network).toHaveRequested()` inspect what the app sent, mocked or not. Each test's traffic is attached to the report as `toets-network.har`. Without the app-side change, the app keeps talking to its real backend and handlers never see a request. Matching, latency and failure helpers: [writing handlers](/reference/mock/docs/writing-handlers). ## Baseline handlers Responses every test needs (config, auth, feature flags) belong in the config, not in each test: ```ts // playwright.config.ts import { defineConfig, http, HttpResponse, platforms } from '@toets/test'; export default defineConfig({ app: { web: { url: 'http://localhost:8080' } }, toets: { mock: { handlers: [http.get('*/api/config', () => HttpResponse.json({ features: [] }))], onUnhandledRequest: 'reject', }, }, projects: [platforms.web()], }); ``` A test's own `app.network.use()` handlers win over them. A project's `toets.mock` merges key by key over the top-level one. ## Traps - **Add handlers before `launch()`** for data the app fetches at startup. Handlers added later only affect later requests. - **A mock that does nothing** usually means the app never routed the request. Check `app.network.requests()`: an absent request went to the real host directly (native players and image loaders often do). - **Assert the screen, then the request.** A request assertion proves the app asked; only the screen proves it showed the result. - **Mock to make tests deterministic**, not to test the backend. Keep a few unmocked smoke tests that exercise real responses. --- # Text input Source: https://yusufyildirim.github.io/toets/concepts/text-input.md A TV has no keyboard. Users type with one of two kinds: - **The system keyboard**, which the platform shows for its own text fields: an `` on web, an `EditText` on Android TV, a `UITextField` on tvOS. toets enters text into these with the platform's text entry (`text.input` capability). - **An app keyboard** (on-screen keyboard, OSK): a grid of focusable keys the app draws itself, common in search and PIN screens. Nothing on the platform knows it is a keyboard, so you **declare** it once with `defineKeyboard()`. toets then types each character the way a user does: D-pad presses to its key, then `SELECT`. The test code is the same for both. toets picks the keyboard for each field. ```ts run import { defineKeyboard, expect, Key, test } from '@toets/test'; // Usually in its own file, passed to defineConfig({ keyboards }). const search = defineKeyboard({ name: 'search', root: { testId: 'osk' }, fields: [{ testId: 'search-input' }], layers: [{ testId: 'osk-layer' }], space: { testId: 'osk-space' }, backspace: { testId: 'osk-del' }, clear: { testId: 'osk-clear' }, submit: { testId: 'osk-search' }, }); test.use({ keyboards: [search] }); test('searches with the app keyboard', async ({ app }) => { await app.launch(); await app.focus.pressUntilFocused(Key.LEFT, app.getByTestId('menu-home')); await app.focus.pressUntilFocused(Key.DOWN, app.getByTestId('menu-search')); await app.remote.press(Key.SELECT); const query = app.getByTestId('search-input'); await query.fill('big buck'); await expect(query).toHaveText('big buck'); await expect(app.keyboard).toBeOpen(); await app.keyboard.type(' 2'); // switches to the digits layer for "2" await app.keyboard.erase(2); await app.keyboard.submit(); await expect(app.getByTestId('search-results')).toHaveText('Results for "big buck"'); await expect(app.keyboard).not.toBeOpen(); }); test('signs in with system text fields', async ({ app }) => { await app.launch(); await app.focus.pressUntilFocused(Key.LEFT, app.getByTestId('menu-home')); await app.focus.pressUntilFocused(Key.DOWN, app.getByTestId('menu-sign-in')); await app.remote.press(Key.SELECT); const email = app.getByTestId('email'); await email.fill('ada@example.com'); await expect(email).toHaveValue('ada@example.com'); await app.getByTestId('password').fill('tv-pass-1'); // reported as ••••••••• await app.keyboard.submit(); await expect(app.getByTestId('sign-in-status')).toHaveText('Signed in as ada@example.com'); }); ``` ## API - `locator.fill(text, { mask })` replaces the field's text: focus moves to the field with real presses, then its keyboard enters the text. It never submits, and returns with no system keyboard covering the app. - `app.keyboard` acts on the keyboard in use: `type(text, { mask })` types at the end, `erase(count)` deletes before the caret with the keyboard's backspace, `submit()` presses its submit key (the action key of the system keyboard: Search, Go, Done). - `toHaveValue(text | RegExp)` asserts the value of a system text field. App keyboards type into ordinary elements: assert those with `toHaveText`. - `expect(app.keyboard).toBeOpen()` asserts that a keyboard is open, with `.not` for closed. - `mask: true` reports the text as `••••` in step titles, errors and MCP output. System password fields mask on their own. There is no `locator.type`, `clear` or `close`: `fill` replaces, `type` appends to the field the keyboard holds, and keyboards close the way the app closes them (`submit()` or `Key.BACK`). ## Which keyboard `fill` uses, in order: 1. The declared keyboard whose `fields` list the field. When it is closed, toets moves focus to the field, presses `SELECT` and tries again. 2. System text entry, when the field is a system text field. 3. Otherwise it fails with `NO_KEYBOARD`. `app.keyboard` uses the declared keyboard holding focus, else system text entry on the focused system text field, else the only declared keyboard on screen. Declarations, layers, speed and the step titles: [text input reference](/reference/core/docs/text-input). ## Traps - **An app keyboard is not a system keyboard.** Typing a search OSK through the platform's text entry would skip the code under test (key handling, layer switching, the app's own field). Declare it, and toets types it with the remote like a user. - **System text entry is not key events.** On web toets inserts text the way an IME does (`insertText`): `input` events fire, `keydown` per character does not. Apps that only listen for `keydown` on a system field see nothing; test that handler with `app.remote.press`. - **Mask secrets.** Step titles, the HTML report, traces and MCP output keep the text. Pass `{ mask: true }` for PINs and passwords typed on app keyboards. `toHaveValue` refuses system password fields (`SECURE_FIELD`): their value is masked by the platform. - **Web has no system keyboard.** There, `app.keyboard` counts as open while a text field holds focus: `fill` on web leaves focus in the field, so `expect(app.keyboard).toBeOpen()` passes until focus moves away. On Android TV and tvOS `fill` closes the system keyboard it opened. - **tvOS password fields reopen empty.** Its fullscreen keyboard starts with an empty entry for a secure field, so `app.keyboard` after a `fill` does not edit the password there. Set a password with one `fill` and submit with the screen's button or another field's action key. - **Keep keyboard declarations free of test imports.** The config loads the `keyboards` file, so it may import only `defineKeyboard` from `@toets/test`. Importing page objects or fixtures from it pulls test code into the config. - **`keyboards` levels replace, not merge.** `defineConfig({ keyboards })`, `platforms.*({ keyboards })` and `test.use({ keyboards })` each replace the level above: list every keyboard at the level you set. - **Old SDKs hide system fields.** With the SDK on, the field's `editable` flag comes from the SDK (protocol 1.1). An older SDK reports none, and `fill` fails with `NO_KEYBOARD`: update the SDK. --- # Deep links Source: https://yusufyildirim.github.io/toets/concepts/deep-links.md A deep link opens the app on a screen: a link in a launcher row, a voice command, a notification, a partner app. toets opens links the way the platform does: the OS resolves the app from its declared URL schemes or intent filters, starts it or delivers the link to the running instance, and the app routes. A test checks that whole chain, not only the router. ```ts run import { expect, Key, requires, test } from '@toets/test'; test('a link starts the app on details', requires('deeplink.launch'), async ({ app }) => { await app.launch({ deepLink: 'demotv://details/sintel' }); // Landing with nothing focused is the classic deep link bug on TV: assert focus first. await expect(app.getByTestId('details-play')).toBeFocused(); await expect(app.getByTestId('details-title')).toHaveText('Sintel'); }); test('a link opens details in the running app', requires('deeplink.open'), async ({ app }) => { await app.launch(); await app.openDeepLink('demotv://details/coffee-run'); await expect(app.getByTestId('details-play')).toBeFocused(); await expect(app.getByTestId('details-title')).toHaveText('Coffee Run'); await app.remote.press(Key.BACK); await expect(app.getByTestId('rail-0-card-0')).toBeFocused(); }); ``` ## One link, translated per platform Tests use **one canonical link**: an absolute URL, usually the app's own scheme (`myapp://details/42`). Where a platform takes another form, the config translates it. Each driver has a `deepLink` mapper, `(link: URL) => ...`, set in `app` or on a project: | Platform | Mapper returns | Default | | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | web | a page URL or path, resolved against `url` | host, path, query and hash as a path (`details/42`); http(s) links: path, query | | Android TV | a URI, or an intent `{ uri, action, categories, mimeType, extras }` | the link as a `VIEW` intent | | tvOS | a URL | the link | ```ts import { defineConfig, platforms } from '@toets/test'; export default defineConfig({ app: { web: { url: 'http://localhost:8080', deepLink: (link) => `/watch${link.pathname}` }, androidTV: { package: 'com.example.tv' }, tvOS: { bundleId: 'com.example.tv' }, }, projects: [ platforms.web(), platforms.androidTV(), platforms.tvOS(), // Fire TV opens content with an intent: a custom action and extras, no URI. platforms.androidTV({ name: 'fire-tv', remote: 'fire-tv', app: { deepLink: (link) => ({ action: 'com.example.PLAY', extras: { contentId: link.pathname.slice(1) }, }), }, }), ], }); ``` The step title shows the translation, and so does the failure dump: `launch (deepLink: myapp://details/42 → intent com.example.PLAY extras { contentId: "42" })`. ## Cold and running - `app.launch({ deepLink })` stops the app and starts it **from the link** (`deeplink.launch`): the system starts the app for the link, as a launcher does. It combines with `state`, `flags` and `clearData`; the launch payload reaches the app as usual. - `app.openDeepLink(url)` delivers the link to the **running** app (`deeplink.open`), which routes without restarting. The app must be launched first. | Platform | `deeplink.launch` | `deeplink.open` | | ---------- | --------------------------------------------------------- | ------------------------------------ | | web | loads the link's page URL instead of `url` | no: a running page receives no links | | Android TV | `am start` of the intent, resolved by the OS | the same intent, app still running | | tvOS | the URL opened in the app, which the system starts for it | the URL opened in the running app | A link no app handles fails with `DEEPLINK_UNHANDLED`, naming the translated form. Details per platform: [deep links reference](/reference/core/docs/deep-links). ## Traps - **Assert focus after landing.** A screen opened from a link often renders with nothing focused, because focus was set by the navigation the link skipped. A test that only checks the title passes while the remote does nothing. Assert `toBeFocused()` on the element a user expects first. - **Trampoline activities must forward extras.** On Android the launch payload rides on the intent as the extra `__toets`. A splash or router activity that starts the real activity with a new intent drops it, and the SDK never connects (`SDK_NOT_CONNECTED`). Copy the extras (`newIntent.putExtras(intent)`) or start the real activity from the link directly. - **Translate, do not branch.** Platform differences in link format belong in the config's mappers. A test that builds `/watch/42` on web and `myapp://details/42` elsewhere tests two different things. - **A link one platform does not have is app scope.** When an app handles a link only on some platforms, run that test only there: a project `testMatch`/`testIgnore` or a tag `grep`. Never translate it into another screen's link on the rest; the test would pass on a screen it does not test. - **Running links are a separate path.** Apps often read the start link and listen for later links in different places (React Native: `Linking.getInitialURL()` and the `url` event; Android: `onCreate` and `onNewIntent`). Test both. --- # Page objects Source: https://yusufyildirim.github.io/toets/concepts/page-objects.md A **page object** names the parts of one screen and the actions a user takes on it, so tests read as intent and a layout change is fixed in one place. In toets a page object is a plain class that takes `app`. ```ts run import { test, expect, Key, type App, type Locator } from '@toets/test'; class HomePage { readonly app: App; readonly screen: Locator; readonly menu: Locator; constructor(app: App) { this.app = app; this.screen = app.getByTestId('home-screen'); this.menu = app.getByTestId('side-menu'); } card(rail: number, index: number): Locator { return this.app.getByTestId(`rail-${rail}-card-${index}`); } async waitUntilLoaded(): Promise { await expect(this.screen).toBeVisible(); } async openCard(rail: number, index: number): Promise { await this.app.focus.pressUntilFocused(Key.DOWN, this.app.getByTestId(`rail-${rail}`)); await this.app.focus.pressUntilFocused(Key.RIGHT, this.card(rail, index)); await this.app.remote.press(Key.SELECT); } } test('opens details from home', async ({ app }) => { await app.launch(); const home = new HomePage(app); await home.waitUntilLoaded(); await home.openCard(0, 2); await expect(app.getByTestId('details-screen')).toBeVisible(); }); ``` ## Rules - **Take `app`, nothing else from the runner.** The same page object then works on every platform and in serial flows. - **Expose locators and actions, not assertions.** Tests decide what is checked. The one exception is waiting until the screen is ready to be driven (`waitUntilLoaded` above) with a stability matcher: `toBeVisible`, `toBeInViewport`, `toBeFocused`, `toHaveFocusWithin`, `toBeBusy`. - **Actions are user intents.** `openCard`, `toggleSubtitles`; not `pressRightThreeTimes`. - **No sleeps, no platform branches.** Adapt through capabilities (`app.platform.has(...)`) if a page object must do something differently. The [ESLint plugin](/reference/eslint-plugin/docs/setup) enforces the assertion rule in page object files (by default anything under `pages/` or named `*Page.*`; see [`page-object-assertions`](/reference/eslint-plugin/docs/rules/page-object-assertions)) and rejects sleeps everywhere. ## Traps - **Do not cache elements.** Store locators, which re-resolve on every use, never values read from the screen. - **A page object per screen, not per platform.** If platforms need different page objects, the app's screens differ; make that explicit with capabilities or separate tests. --- # The in-app SDK Source: https://yusufyildirim.github.io/toets/concepts/sdk.md toets works **black-box**: the first test needs no app changes. The optional **SDK** is a small library inside the app that talks to the test host and reports what the app itself knows. It makes tests faster and more reliable, and adds capabilities a black-box driver can not offer. One exception: an app whose focus lives in a **JS focus engine** (Norigin Spatial Navigation, LRUD, react-tv-space-navigation, ...) has no focus a driver can see. It reports focus through the SDK with `reportFocus()` ([reporting focus](/reference/sdk/docs/focus)). | Domain | Adds | Capability | | ------- | ------------------------------------------------------- | ---------------- | | `tree` | uniform element tree, free of accessibility-tree quirks | `tree.hierarchy` | | `focus` | the app's real focus, including app-reported focus | | | `sync` | idle signal, busy resources | `sync.idle` | | `media` | player state, position, duration, errors | `media.state` | | `state` | launch into a named state, feature flags | `app.state` | | `logs` | console output and unhandled errors on the test result | `logs` | ## How it connects Turn it on with `toets: { sdk: true }` in the config, and start the SDK in the app. On every launch the test host passes a launch payload to the app (SDK host URL, launch token, mock server URL, state). The SDK reads it, connects to the host over WebSocket, and announces the domains it implements; `launch()` waits for that connection and fails with `SDK_NOT_CONNECTED` if it never comes. Without a valid payload the SDK does nothing: it never opens a connection in normal use. Exclude it from production builds anyway. Packages: [`@toets/sdk`](/reference/sdk) (framework-neutral core and web adapter) and [`@toets/sdk-react-native`](/reference/sdk-react-native). Any framework can implement the [protocol](/reference/protocol); a conformance suite verifies it. ## Named states With `state`, a test starts where it needs to be instead of clicking through onboarding: ```ts run import { test, expect, requires } from '@toets/test'; test('resumes from the continue-watching rail', requires('app.state'), async ({ app }) => { await app.launch({ state: 'signed-in-with-history' }); await expect(app.getByTestId('rail-continue-watching')).toBeVisible(); }); ``` The app defines what each state name means (`onState` in the SDK, see [app state](/reference/sdk/docs/state)); toets only delivers the name and any `flags`. ## Traps - **The SDK never sends input.** Keys always go through the platform, so the native focus engine is exercised. The SDK only observes and prepares state. - **Keep black-box tests passing.** A test that needs the SDK says so with `requires`. Do not make the whole suite depend on it by accident. - **Do not ship it.** Guard the SDK behind a debug or test build flag so production bundles exclude it. --- # Text snapshots Source: https://yusufyildirim.github.io/toets/concepts/text-snapshots.md A **text snapshot** is a YAML rendering of the screen or one element: test IDs, text and state, with the focused element marked. It is deterministic and comparable across platforms, so it serves three purposes: - **Failure context.** Every failure dump includes one; an agent reads it instead of a screenshot. - **Exploration.** `app.snapshot()` (and the MCP server's `snapshot` tool) shows what is on screen and what is focusable. - **Assertions.** Compare a region against a stored snapshot to lock down structure. ```yaml - rail-0: - rail-0-card-0 "Big Buck Bunny" - rail-0-card-1 "Sintel" [focused] - rail-1: - rail-1-card-0 "Tears of Steel" ``` One line per visible element: its test ID (else its text), its text in quotes and its state in brackets. Exact rules: [text snapshots reference](/reference/core/docs/text-snapshots). ```ts run import { test, expect } from '@toets/test'; test('home rail lists the mocked titles', async ({ app }) => { await app.launch(); await expect(app.getByTestId('rail-0')).toMatchTextSnapshot(` - rail-0: - rail-0-card-0 "Big Buck Bunny" [focused] - rail-0-card-1 "Sintel" - rail-0-card-2 "Tears of Steel" - rail-0-card-3 "Elephants Dream" `); }); ``` With a string, the snapshot is compared inline (indentation ignored). Without one, it is compared to a baseline file per project, written (and failed) on the first run like any Playwright snapshot and updated with `--update-snapshots`. ## Traps - **Snapshot a region, not the screen.** Whole-screen snapshots break on unrelated changes. Pick the element whose structure the test is about. - **Nesting follows the tree.** Black-box native trees can flatten containers (a React Native `View` lists its children as its siblings), so a snapshot spanning them only has the same shape where the tree nests: declare `requires('tree.hierarchy')` (the DOM and the SDK tree), or snapshot an element that keeps its children everywhere. - **Mock the data first.** A snapshot of live content changes with the content. Use [network mocking](/concepts/network-mocking). - **Inline snapshots serve all platforms** when the app uses the same test IDs everywhere; where platforms legitimately differ, the diff shows it. Baseline files are per project and never carry the host OS (toets drops Playwright's `-darwin` / `-linux` suffix), so baselines written on a laptop match in CI. --- # Writing tests Source: https://yusufyildirim.github.io/toets/guides/writing-tests.md A good toets test drives the app the way a user does with a remote, checks what the user would see, and means the same thing on every platform. ## Shape 1. **Arrange**: mock the data, launch (into a named state if the SDK provides one). 2. **Act**: move focus and press keys. 3. **Assert**: focus, visibility, text, media state. After every navigation step, assert where focus landed. ## Principles - **One behavior per test.** Name it after the behavior: `'remembers focus when returning to a rail'`. - **Independent tests.** Each test sets up what it needs. Share state only through [serial flows](/guides/serial-flows), and only when it is the point. - **Navigate like a user.** Focus and keys only; there is no click. Use [`navigateTo`](/concepts/focus) to get somewhere, explicit presses when navigation is the behavior. - **Locate by test ID.** Text for user-facing copy only. See [Locators and assertions](/concepts/locators-and-assertions). - **Let assertions wait.** Never sleep, never poll by hand. Anchor negative assertions on a positive one. See [Idle](/concepts/idle). - **Make data deterministic** with [network mocking](/concepts/network-mocking). - **Declare platform needs** with `requires`, never with `if (platform)`. See [Capabilities](/concepts/capabilities). - **Name screens with [page objects](/concepts/page-objects)** once more than one test touches them. ## App-specific setup belongs in your fixtures toets knows nothing about your splash screen, sign-in or consent dialogs. Put that in a Playwright fixture in your project and build tests on it: ```ts run import { test as base, expect, type App } from '@toets/test'; /** The app launched and past the splash screen. */ export const test = base.extend<{ home: App }>({ home: async ({ app }, use) => { await app.launch(); await expect(app.getByTestId('home-screen')).toBeVisible({ timeout: 30_000 }); await use(app); }, }); test('home shows the featured rail first', async ({ home }) => { await expect(home.getByTestId('rail-0')).toHaveFocusWithin(); }); ``` ## The fast loop Develop against web (`--project=web`): it starts in seconds and records Playwright traces. Then run every project before you finish; a test is done when it passes, or is skipped with a reason, everywhere (check `toets-report/parity.md`). ```sh npx playwright test e2e/home.spec.ts --project=web npx playwright test e2e/home.spec.ts ``` Enable the [ESLint plugin](/reference/eslint-plugin/docs/setup): it rejects sleeps, raw keycodes and behavior assertions in page objects, and warns on `platformOnly`. ## Traps - **Passing on web is not passing.** Emulators are slower, focus engines differ and some keys do not exist. Run all platforms. - **A test that never fails is not testing.** After writing an assertion, break the condition once (wrong test ID, wrong expected text) and see it fail with a useful message. - **Do not reach for `platformOnly`.** If a test needs it, the gap is a missing capability or an app testability issue; fix that instead. --- # Debugging failures Source: https://yusufyildirim.github.io/toets/guides/debugging-failures.md toets failures are meant to explain themselves. Read what they say before changing the test. ## 1. Read the failure - **The error.** A thrown error reads `ToetsError: [CODE] what happened`, then `Hint:` (likely cause and fix) and `Docs:` (the page, with its offline path). Every code is listed in the [error code index](/reference/core/docs/errors). A failed assertion shows the locator, expected and received state, what was focused and whether the app was idle. - **The failure dump** (`toets-failure.md`, with `toets-screenshot.png`), in the failed test's `test-results/` folder and attached to the report: platform and capabilities, the focused element, a [text snapshot](/concepts/text-snapshots) of the screen, the last keys pressed, what kept the app busy, recent logs and requests. See [failure dumps](/reference/core/docs/failure-dumps). - **The report.** `npx playwright show-report` lists every action as a step (`press RIGHT`, `pressUntilFocused RIGHT getByTestId('card')`). Per test: `toets-logs` and, with mocking on, `toets-network.har`. Per-step screenshots and snapshots (`toets.steps`) and video (`toets.video`) are off by default; turn them on while debugging. Web runs also record Playwright traces (`--trace on`). ## 2. Reproduce narrowly ```sh npx playwright test e2e/home.spec.ts:12 --project=android-tv --retries=0 npx playwright test e2e/home.spec.ts --project=web --ui npx playwright test e2e/home.spec.ts --repeat-each=10 # is it flaky? ``` To look at the live app with the same primitives, use the [MCP server](/reference/mcp): launch, press, snapshot. ## 3. Match the symptom | Symptom | Look at | | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | Element not found on one platform | The text snapshot: is the test ID there? See the test ID mapping in [Locators](/concepts/locators-and-assertions). | | Focus on the wrong element | The step screenshots and last keys. An overlay or a different focus engine rule on that platform. | | `FOCUS_STUCK`, `FOCUS_LOOP`, `FOCUS_UNREACHABLE` | Where focus went, in the message. Stuck: end of a row, a trap, a disabled target. Loop: the target is not in that direction. | | Timed out, busy resource named | The app never went idle: a poller, animation or player. Exclude the noise in the SDK. | | `KEY_UNSUPPORTED` | The platform lacks it. Declare `requires`, or configure an override. See [Remote and keys](/concepts/remote-and-keys). | | Negative assertion passes, then the bug appears | It passed too early. Anchor it on a positive assertion. See [Idle](/concepts/idle). | | Passes on web, fails on a device | Compare text snapshots across platforms; check device logs for app errors. | | Launch fails | Driver and device logs; the `app` config for that platform; see [Platforms](/platforms/web). | ## Traps - **Do not raise the timeout** unless the operation is legitimately slow. Most timeouts are wrong state, not slowness. - **Do not add sleeps or retries** to make a flaky test pass. Find what the test raced against. - **Do not weaken the assertion** to match buggy behavior. If the app is wrong, the test should keep failing; report the bug. - **Check the app first** when a test that used to pass fails everywhere at once. --- # Serial flows Source: https://yusufyildirim.github.io/toets/guides/serial-flows.md By default every test is independent. A **serial flow** groups tests that run in order, in one worker, on **one shared `app`**: each test continues where the previous one left off. The semantics are Playwright's serial mode, identical on every platform. ```ts run import { test, expect, Key } from '@toets/test'; test.describe.serial('first run', () => { test('accepts the terms', async ({ app }) => { await app.launch({ clearData: true }); await app.focus.navigateTo(app.getByTestId('terms-accept')); await app.remote.press(Key.SELECT); await expect(app.getByTestId('profile-picker')).toBeVisible(); }); test('picks a profile and lands on home', async ({ app }) => { await app.focus.navigateTo(app.getByTestId('profile-0')); await app.remote.press(Key.SELECT); await expect(app.getByTestId('home-screen')).toBeVisible(); }); }); ``` ## Semantics - Tests in the group share one `app` and run in declaration order. - When one fails, the rest of the group is skipped. - Retries rerun the whole group from the start. ## When to use For journeys whose steps are the subject of the test and can not be reached directly: first-run onboarding, a purchase that changes what later screens show. Each test is a checkpoint with its own name in the report. Prefer independent tests otherwise. If the only reason for a serial flow is to skip setup, launch into a [named state](/concepts/sdk#named-states) instead. ## Traps - **Serial flows hide dependencies.** A test in the middle can not run alone. Keep groups short and self-contained in one `describe`. - **Order across files is not guaranteed.** Never rely on another file's tests having run. - **A failure early skips everything after it.** Put the most important checks where they run first, or split the flow. --- # Migrating from Playwright Source: https://yusufyildirim.github.io/toets/guides/migrating/from-playwright.md toets runs on Playwright Test, so the runner, config, reporters, UI mode, `test.step`, fixtures and `expect` style carry over. What changes is the model of the app: `page` becomes `app`, and the pointer is replaced by focus and the remote. | Playwright | toets | | ------------------------------------------------- | ---------------------------------------------------------------------------------- | | `import { test, expect } from '@playwright/test'` | `import { test, expect, Key } from '@toets/test'` | | `{ page }` fixture | `{ app }` fixture | | `page.goto(url)` | `app.launch()`; the URL lives in the config (`app.web.url`) | | `page.getByTestId(id)`, `page.getByText(t)` | `app.getByTestId(id)`, `app.getByText(t)` | | `locator.click()` | `app.focus.pressUntilFocused(Key.X, locator)`, then `app.remote.press(Key.SELECT)` | | `page.keyboard.press('ArrowRight')` | `app.remote.press(Key.RIGHT)` | | `locator.fill(text)` | no equivalent in v1; drive the on-screen keyboard with focus and keys | | `page.route(url, handler)` | `app.network.use(http.get(url, handler))` | | `expect(locator).toBeVisible()` | the same | | `expect(locator).toBeFocused()` | the same, and central: assert it after every navigation | | `page.evaluate(fn)` | none; `app.platformOnly('web', ...)` as a marked last resort | | `projects: [{ use: devices['...'] }]` | `projects: [platforms.web(), platforms.androidTV(), platforms.tvOS()]` | ## Principles - **Rewrite clicks as navigation.** A click says "activate this"; on TV the user first has to get there. Decide whether getting there is part of the behavior (explicit presses) or not (`pressUntilFocused`, `navigateTo`). - **Drop `getByRole` and CSS selectors.** v1 locates by test ID and text only, because those mean the same on every platform. Add test IDs to the app where needed. - **Remove web-only assumptions.** Viewport sizes, hover states, `page.evaluate` and DOM access do not exist on Android TV or tvOS. ## Traps - **Keyboard key names are not remote keys.** `Enter` is not `SELECT` on every platform; `Escape` is not `BACK`. Use `Key` and let the driver map it. - **Network mocking needs the app's cooperation.** `page.route` intercepts in the browser; toets's mock server works on every platform but is off until `toets: { mock: true }`, and the app must send traffic to it. See [Network mocking](/concepts/network-mocking). --- # Migrating from Appium / WebdriverIO Source: https://yusufyildirim.github.io/toets/guides/migrating/from-appium.md toets uses Appium underneath on Android TV and tvOS, but tests never see it. Sessions, capabilities JSON, keycodes and emulator ports are replaced by a config, semantic keys and a device pool, and the runner is Playwright Test. | Appium / WebdriverIO | toets | | --------------------------------------------------- | -------------------------------------------------------------------------------- | | Capabilities JSON per platform | `app` entries and `platforms.*()` projects in `defineConfig` | | Mocha or Jest runner | Playwright Test | | `$('~id')`, `$('id=com.example:id/x')` | `app.getByTestId('x')` | | `$('android=new UiSelector().text("Play")')` | `app.getByText('Play')` | | `driver.pressKeyCode(22)` | `app.remote.press(Key.RIGHT)` | | `$('~play').click()` | `app.focus.pressUntilFocused(Key.X, app.getByTestId('play'))`, then `Key.SELECT` | | `el.waitForDisplayed()`, `browser.waitUntil(...)` | `await expect(locator).toBeVisible()` | | `driver.activateApp(id)`, `driver.terminateApp(id)` | `app.launch()`, `app.terminate()` | | `mobile: shell` with `dumpsys` for player state | `await expect(app.media).toBePlaying()` (`media.state`) | | Booting emulators and port math in scripts | the device pool: one device per worker, reset between tests | ## Principles - **Keycodes become semantic keys.** toets maps them per platform and refuses, with a capability error, what the remote lacks. See [Remote and keys](/concepts/remote-and-keys). - **Explicit waits become assertions.** Matchers retry with a timeout; remove `pause()` and `waitUntil` loops entirely. - **Platform selectors become test IDs.** One locator per element for all platforms. If Android and tvOS tests used different selectors, give the element one test ID. - **Parallelism is free.** Each worker gets its own device, so drop serial-only setups. ## Traps - **Do not port `element.click()` literally.** Appium's click on TV often bypasses focus. toets always moves focus with the remote, which may expose real focus bugs your old tests skipped. - **Shell commands are gone on purpose.** Needs like player state, app state or OS events have capabilities (`media.state`, `app.state`, `platform.events`). See [Capabilities](/concepts/capabilities). --- # Migrating from Detox Source: https://yusufyildirim.github.io/toets/guides/migrating/from-detox.md Detox and toets share the gray-box idea: an in-app component reports when the app is idle. The differences: toets runs on Playwright Test, targets TV platforms including web, drives the app with a remote instead of touch, and treats idle as an accelerator rather than a gate. | Detox | toets | | ------------------------------------------------------- | ---------------------------------------------------------------------------------- | | Jest runner, `.detoxrc` configurations | Playwright Test, `defineConfig` with `platforms.*()` projects | | `element(by.id('x'))`, `element(by.text('Play'))` | `app.getByTestId('x')`, `app.getByText('Play')` | | `.atIndex(n)` | `.nth(n)` | | `.tap()` | `app.focus.pressUntilFocused(Key.X, locator)`, then `app.remote.press(Key.SELECT)` | | `.typeText(text)` | no equivalent in v1; drive the on-screen keyboard | | `expect(el).toBeVisible()` | `await expect(locator).toBeVisible()` | | `waitFor(el).toBeVisible().withTimeout(5000)` | `await expect(locator).toBeVisible({ timeout: 5000 })` | | `device.launchApp({ newInstance: true, delete: true })` | `app.launch({ clearData: true })` | | `device.launchApp({ launchArgs })` | `app.launch({ state, flags })` | | `device.pressBack()` | `app.remote.press(Key.BACK)` | | Automatic synchronization | SDK idle (`sync.idle`), plus assertions that always retry | ## Principles - **Taps become navigation.** Decide per step whether reaching the element is part of the behavior (explicit presses) or not (`pressUntilFocused`, `navigateTo`), and assert focus. - **Idle never blocks.** Detox waits for idle before every action and hangs when the app never settles. toets uses idle to check sooner and falls back to polling, naming the busy resource. See [Idle](/concepts/idle). - **The SDK is optional.** Start black-box; add the [SDK](/concepts/sdk) for idle, media state and named states (and to report focus from a JS focus engine). ## Traps - **`await` every assertion.** Detox `expect` is async too, but Playwright reports an un-awaited assertion as a passing test that checked nothing. - **Launch arguments are not states.** Detox `launchArgs` reach the app however you wire them; toets delivers `state` and `flags` through the launch payload, and the app applies them through the SDK. --- # Web Source: https://yusufyildirim.github.io/toets/platforms/web.md Runs the app in Chromium through Playwright. It is the fastest platform to start and the only one with full Playwright traces, so it is where tests are usually written first. Package: [`@toets/driver-web`](/reference/driver-web). ```ts import { defineConfig, platforms } from '@toets/test'; export default defineConfig({ app: { web: { url: 'http://localhost:8080' } }, projects: [platforms.web()], }); ``` The app must already be served at `url`; start it with Playwright's [`webServer`](https://playwright.dev/docs/test-webserver) option or in your CI job. | Aspect | Web | | --------- | ------------------------------------------------------------------------- | | Test ID | `data-testid` | | Focus | `document.activeElement`, or the SDK's focus when connected | | Keys | `KeyboardEvent`s; the key mapping is configurable for TV web keycodes | | Launch | navigates to `url` with the launch payload as a `__toets` query parameter | | Artifacts | Playwright trace (`--trace on`), video, console logs | Options (test ID attribute, key map, viewport, launch transport): [web driver options](/reference/driver-web/docs/options). ## Traps - **Desktop Chromium is not a TV browser.** It is modern Chromium, not the engine of a given TV OS. Old-engine coverage (Tizen, webOS) is a later phase. - **Apps that listen to `keyCode`.** Many TV web apps read legacy key codes (for example 461 for back on webOS). Configure the driver's [key map](/reference/driver-web/docs/keys) to match what your app expects. - **Virtual focus.** Apps whose JS focus engine highlights elements without moving DOM focus report focus through the [SDK](/concepts/sdk) with `reportFocus()`; without it, focus assertions see nothing. - **Do not lean on the trace viewer for parity.** Other platforms have step screenshots and text snapshots instead; make failures understandable from those. --- # Android TV / Fire TV Source: https://yusufyildirim.github.io/toets/platforms/android-tv.md Runs the app on Android TV emulators through Appium UiAutomator2. toets manages the Appium server and, by default, the emulators: one per worker, created from an Android TV system image, snapshotted and reset between tests. Package: [`@toets/driver-android-tv`](/reference/driver-android-tv). ```ts import { defineConfig, platforms } from '@toets/test'; export default defineConfig({ app: { androidTV: { apk: './build/app-debug.apk', package: 'com.example.tv' } }, projects: [platforms.androidTV({ model: 'tv_1080p', osVersion: '34' })], }); ``` **Host:** the Android SDK with an Android TV system image, and hardware acceleration (macOS, or Linux with KVM). See [Android TV on Linux](/ci/android) for CI. | Aspect | Android TV | | --------- | ------------------------------------------------------------------------------------- | | Test ID | view resource ID | | Focus | the focused view, or the SDK's focus when connected | | Keys | Android keycodes; all TV keys including color, numeric, channel and media | | Launch | launch payload as the `__toets` intent extra; host ports forwarded with `adb reverse` | | Artifacts | logcat, screen recording (`toets.video`) | Options (SDK path, Appium, remote profile, logcat, managed emulators): [Android TV setup](/reference/driver-android-tv/docs/setup) and [devices](/reference/driver-android-tv/docs/devices). ## Devices | Mode | Who owns the emulator | | ---------- | ------------------------------------------------------------------------------------------------------ | | `managed` | toets: creates, boots, snapshots, resets and shuts down emulators (default) | | `external` | you: running devices, `devices: { mode: 'external' }` with `TOETS_DEVICES=emulator-5554,emulator-5556` | | `command` | your scripts: shell commands lease and release devices (device farms, lease brokers) | ## Fire TV Fire TV apps (Fire OS) are Android apps; test them on Android TV emulators with `platforms.androidTV({ remote: 'fire-tv' })`, which limits the keys to the Alexa Voice Remote's. Amazon services (IAP, ADM) are not on Android TV images; fake them in the app's test build. Vega OS is not supported. See [Fire TV](/reference/driver-android-tv/docs/fire-tv). ## Traps - **Emulators need hardware acceleration.** Without KVM or the macOS hypervisor they are too slow to be useful. - **First boot is slow; later boots are not.** Managed mode snapshots a booted emulator and restores it. Keep the AVD and snapshot cached in CI. - **`localhost` on the device is the device.** toets forwards the ports in the launch payload; if your app talks to other host services (Metro for React Native debug builds), list their ports in `reversePorts` or use the mock server. See [traps](/reference/driver-android-tv/docs/traps). - **Resource IDs need to be set.** Views without an ID are invisible to `getByTestId`; React Native sets it from `testID`. --- # tvOS Source: https://yusufyildirim.github.io/toets/platforms/tvos.md Runs the app on Apple TV simulators through Appium XCUITest. toets manages the Appium server and, by default, the simulators: one per worker, reset between tests. Package: [`@toets/driver-tvos`](/reference/driver-tvos). ```ts import { defineConfig, platforms } from '@toets/test'; export default defineConfig({ app: { tvOS: { app: './build/Example.app', bundleId: 'com.example.tv' } }, projects: [platforms.tvOS({ osVersion: '18' })], }); ``` **Host:** macOS with Xcode and a tvOS simulator runtime. The `.app` must be built for the simulator (`-sdk appletvsimulator`). See [tvOS on macOS](/ci/tvos) for CI. | Aspect | tvOS | | --------- | --------------------------------------------------------------------------------------- | | Test ID | `accessibilityIdentifier` | | Focus | the element with focus, or the SDK's focus when connected | | Keys | Siri Remote buttons only | | Launch | launch payload as the `-__toets` launch argument; the simulator shares the host network | | Artifacts | simulator logs, screen recording (`toets.video`) | `osVersion` is a tvOS version prefix (`18` matches 18.x); `model` an Apple TV device type name. Options: [tvOS setup](/reference/driver-tvos/docs/setup) and [simulators](/reference/driver-tvos/docs/simulators). ## Keys The remote has up, down, left, right, select, back (the Menu button), play/pause and home, and buttons can be held. So `key.back`, `key.home`, `key.media.toggle` and `key.longpress` are available; color, numeric, channel, info, menu, discrete media, seek and track keys are not. Tests that need them are skipped here with a reason. If your app implements, say, fast-forward as "hold right", declare a [key override](/concepts/remote-and-keys#overrides). ## Traps - **The focus engine is strict.** tvOS only focuses elements the app marks focusable, and moves by its own geometry rules. A test that passes on web can fail here for real reasons. - **Presses right after a screen change are lost.** Until the new screen holds focus, the remote does nothing. Assert focus on it (`toBeFocused`), not just visibility, before the next press. - **First run builds WebDriverAgent.** It takes about a minute once per Xcode version (cached in `~/Library/Caches/toets/tvos-wda`); cache that folder in CI. - **`BACK` on the home screen leaves the app.** As on a real Apple TV. --- # CI recipes Source: https://yusufyildirim.github.io/toets/ci/index.md toets ships no CI actions: these pages are recipes to adapt to your provider. The examples use GitHub Actions because it is common; the principles carry over. ## Principles - **One job per platform host.** Web runs anywhere, Android TV needs Linux with KVM (or macOS), tvOS needs macOS. Split by `--project`. - **Build the app once.** Build the web bundle, APK and simulator `.app` in their own jobs, pass them as artifacts, and point the `app` config at them. - **Size workers to devices.** Each worker leases one emulator or simulator. An Android TV emulator wants about 2 vCPUs and 3 GB of RAM; set `workers` to what the runner can host and shard across jobs for more. - **Cache what is slow and deterministic.** System images, AVD snapshots, WebDriverAgent, browsers. See [Caching](/ci/caching). - **Always keep the report**, especially when the job fails. See [Artifacts and reports](/ci/artifacts). - **Retries are a signal, not a fix.** Allow at most one retry in CI, and treat tests the report marks flaky as bugs. ```ts import { defineConfig, platforms } from '@toets/test'; const ci = Boolean(process.env.CI); export default defineConfig({ testDir: './e2e', retries: ci ? 1 : 0, workers: ci ? 2 : '50%', reporter: ci ? [['blob'], ['github']] : 'html', app: { web: { url: 'http://localhost:8080' }, androidTV: { apk: './build/app-debug.apk', package: 'com.example.tv' }, tvOS: { app: './build/Example.app', bundleId: 'com.example.tv' }, }, projects: [ platforms.web(), platforms.androidTV({ osVersion: '34' }), platforms.tvOS({ osVersion: '18' }), ], }); ``` ## Recipes - [Android TV on Linux](/ci/android) - [tvOS on macOS](/ci/tvos) - [Caching](/ci/caching) - [Artifacts and reports](/ci/artifacts) The web project needs nothing beyond `npx playwright install --with-deps chromium` and your app served at the configured URL. --- # Android TV on Linux Source: https://yusufyildirim.github.io/toets/ci/android.md Android TV emulators need hardware virtualization. On Linux that means **KVM on an x86_64 runner**; without it the emulator falls back to software emulation and is too slow to use. GitHub-hosted Ubuntu runners support KVM once it is enabled for the runner user. ```yaml jobs: android-tv: runs-on: ubuntu-24.04 timeout-minutes: 45 env: ANDROID_TV_IMAGE: system-images;android-34;android-tv;x86 steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5 with: node-version: 24 cache: npm - name: Enable KVM run: | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' \ | sudo tee /etc/udev/rules.d/99-kvm4all.rules sudo udevadm control --reload-rules sudo udevadm trigger --name-match=kvm - name: Install emulator and Android TV image run: | sdkmanager="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" yes | "$sdkmanager" --licenses > /dev/null "$sdkmanager" emulator platform-tools "$ANDROID_TV_IMAGE" - uses: actions/download-artifact@v5 with: name: app-apk path: build - run: npm ci - run: npx playwright test --project=android-tv - uses: actions/upload-artifact@v4 if: ${{ !cancelled() }} with: name: report-android-tv path: | playwright-report test-results toets-report ``` ## Adapting it - **Pick the image** with `sdkmanager --list | grep -E 'android-tv|google-tv'` and keep it in one variable. Match `osVersion` (the API level) in your config. - **Managed mode does the rest.** toets creates the AVD, boots it headless, snapshots it and resets it between tests. On headless Linux runners without a GPU, pass `managed: { emulatorArgs: ['-gpu', 'swiftshader_indirect'] }`. Use `external` mode only if your CI already provides running emulators. - **Workers:** with software rendering (`swiftshader_indirect`) on a 4 vCPU runner, run 1 worker per job and shard across jobs (`--shard=1/3`) rather than adding workers. - **Cache** `$ANDROID_HOME/emulator` and the system image (and `~/.android/avd` only on homogeneous runners); see [Caching](/ci/caching). ## Traps - **arm64 Linux runners** usually lack nested virtualization. Use x86_64 runners and x86 images. - **AVD snapshots are CPU-bound.** Caching `~/.android/avd` across heterogeneous cloud VMs can hang on boot; let each runner cold-boot once from a cached system image instead. - **Emulator crashes look like test failures.** Check the device logs attached to the first failing test before debugging the test. --- # tvOS on macOS Source: https://yusufyildirim.github.io/toets/ci/tvos.md tvOS simulators run only on macOS with Xcode. A CI job selects an Xcode version, makes sure the tvOS simulator runtime is installed, builds the app for the simulator and runs the `tvos` project. ```yaml jobs: tvos: runs-on: macos-15 timeout-minutes: 60 steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v5 with: node-version: 24 cache: npm - name: Select Xcode run: sudo xcode-select -s /Applications/Xcode_16.4.app - name: Ensure the tvOS simulator runtime run: xcrun simctl list runtimes | grep -q tvOS || xcodebuild -downloadPlatform tvOS - name: Build for the simulator run: | xcodebuild -workspace ios/Example.xcworkspace -scheme Example-tvOS \ -sdk appletvsimulator -configuration Debug -derivedDataPath build/xcode cp -R build/xcode/Build/Products/Debug-appletvsimulator/Example.app build/ - run: npm ci - run: npx playwright test --project=tvos - uses: actions/upload-artifact@v4 if: ${{ !cancelled() }} with: name: report-tvos path: | playwright-report test-results toets-report ``` ## Adapting it - **Pin Xcode** and the tvOS runtime together; match `osVersion` in your config. Runner images change their default Xcode over time. - **Managed mode** creates and boots Apple TV simulators and resets them between tests. On 3-4 vCPU Apple Silicon runners, 1 worker per job sharded across jobs (`--shard=1/3`) avoids CPU contention. - **Build once, for the runner's architecture.** Compile only `arm64` on Apple Silicon runners (`ARCHS=arm64 ONLY_ACTIVE_ARCH=YES`) to cut build time, and pass the `.app` bundle (as a tar archive to preserve symlinks and permissions) as an artifact to E2E jobs. - **Cache** WebDriverAgent and Appium drivers; see [Caching](/ci/caching). ## Traps - **The first run builds WebDriverAgent**, which takes minutes. Without a cache, every run pays it. - **Device builds do not run on simulators.** The `.app` must come from `-sdk appletvsimulator`. - **macOS minutes are expensive.** Run the fast web project first and gate the tvOS job on it. --- # Caching Source: https://yusufyildirim.github.io/toets/ci/caching.md Device-backed runs spend most of their setup time downloading and booting. Cache what is **slow and deterministic**, and key each cache by exactly the inputs that change it. | What | Path (typical) | Key by | | --------------------- | -------------------------------------------------------------------------- | ----------------------------------------- | | Package manager store | handled by `actions/setup-node` `cache:` | lockfile hash | | Playwright browsers | `~/.cache/ms-playwright` (Linux), `~/Library/Caches/ms-playwright` (macOS) | Playwright version | | Android system image | `$ANDROID_HOME/system-images`, `$ANDROID_HOME/emulator` | image ID | | AVD and boot snapshot | `~/.android/avd` (homogeneous runners only) | image ID, emulator version, toets version | | WebDriverAgent build | `~/Library/Caches/toets/tvos-wda` | toets version, Xcode version | | App build | your build output | hash of the app's sources | ```yaml # Only cache ~/.android/avd when every runner has the same host CPU (e.g. self-hosted). # On heterogeneous cloud runners, cache $ANDROID_HOME/emulator and the system image instead. - uses: actions/cache@v4 with: path: ~/.android/avd key: avd-${{ runner.os }}-${{ env.ANDROID_TV_IMAGE }}-${{ env.CACHE_EPOCH }}-${{ hashFiles('package-lock.json') }} ``` ## Traps - **Snapshots are not portable across CPUs.** An AVD snapshot taken on one host CPU or emulator version can fail or hang on boot on another VM. On heterogeneous cloud runners (such as GitHub-hosted Ubuntu runners), cache `$ANDROID_HOME/emulator` and the system image, not `~/.android/avd`. Only cache AVD snapshots on homogeneous self-hosted runners, and include the emulator version in the key. - **Do not cache app data or test results.** Each run must start from a clean device state; toets resets devices for that reason. - **Restore keys can hide breakage.** A partial match may restore a cache built for another image or Xcode. Prefer exact keys for device caches. --- # Artifacts and reports Source: https://yusufyildirim.github.io/toets/ci/artifacts.md toets reports through Playwright: each action is a `test.step`, and each test carries device logs, its network log (with mocking) and, on failure, a failure dump and screenshot as attachments; per-step screenshots and video are opt-in (`toets.steps`, `toets.video`). The parity matrix is written to `toets-report/`. In CI, keep all of it, especially when the job fails. ## Upload always Upload `playwright-report/`, `test-results/` and `toets-report/` on every run that was not cancelled, not only on failure; the parity matrix and flaky markers matter on green runs too. ```yaml - uses: actions/upload-artifact@v4 if: ${{ !cancelled() }} with: name: report-${{ matrix.project }}-${{ strategy.job-index }} path: | playwright-report test-results toets-report retention-days: 14 ``` ## Sharding and merging Shard a platform across jobs with `--shard=/` and the `blob` reporter (set it in the config: `--reporter` on the command line drops the parity reporter), then merge in a final job. Add the parity reporter to the merge to get one matrix for all shards and platforms: ```sh npx playwright test --project=android-tv --shard=1/3 npx playwright merge-reports --reporter html,@toets/test/reporter ./all-blob-reports ``` ## Reading the report - **Parity matrix:** which test ran on which platform, and the reason for every skip. - **Steps:** every key press, navigation and launch, with a screenshot and text snapshot when `toets.steps` is on. - **Failure dump:** focused element, surrounding tree, last keys, logs and requests. Start here; see [Debugging failures](/guides/debugging-failures). ## Traps - **Videos are large.** Record on failure or first retry rather than always, and set a retention period. - **Reports from different platforms belong together.** Merge them so one report shows the whole parity matrix. --- # Reference Source: https://yusufyildirim.github.io/toets/reference/index.md Each package documents itself in its own `docs/` folder. The same pages ship inside the npm package, so an installed version always has matching docs at `node_modules/@toets//docs/`. This section renders them. | Package | Role | | ---------------------------------------------------- | -------------------------------------------------------------------- | | [`@toets/test`](/reference/test) | Main entry: `test`, `expect`, `Key`, `defineConfig`, `platforms` | | [`@toets/core`](/reference/core) | Platform-neutral core: locators, matchers, focus, keys, capabilities | | [`@toets/driver-web`](/reference/driver-web) | Web driver (Chromium through Playwright) | | [`@toets/driver-android-tv`](/reference/driver-android-tv) | Android TV driver (Appium UiAutomator2) and emulator management | | [`@toets/driver-tvos`](/reference/driver-tvos) | tvOS driver (Appium XCUITest) and simulator management | | [`@toets/mock`](/reference/mock) | Host-side mock server with MSW handlers | | [`@toets/protocol`](/reference/protocol) | SDK protocol spec, host and conformance suite | | [`@toets/sdk`](/reference/sdk) | In-app SDK core and web adapter | | [`@toets/sdk-react-native`](/reference/sdk-react-native) | In-app SDK adapter for React Native | | [`@toets/mcp`](/reference/mcp) | MCP server for agents | | [`@toets/eslint-plugin`](/reference/eslint-plugin) | Lint rules for toets tests and page objects | Every error code a toets error can carry is listed in [Error codes](/reference/core/docs/errors). There is no generated API site yet: the type declarations each package ships (`dist/*.d.ts`) carry the TSDoc and are the API reference; editors and agents read them directly. --- # The `app` fixture Source: https://yusufyildirim.github.io/toets/reference/test/docs/app-fixture.md Every test gets `app`, the app under test on the project's platform. It is the only fixture a toets test needs. ```ts run import { test, expect, Key } from '@toets/test'; test('opens details', async ({ app }) => { await app.launch(); await app.focus.pressUntilFocused(Key.RIGHT, app.getByTestId('rail-0-card-1')); await app.remote.press(Key.SELECT); await expect(app.getByTestId('details-title')).toBeVisible(); }); ``` ## Lifecycle - **Per worker:** the device lease, driver session, mock server and SDK host start on the first test that needs them and stop when the worker exits. Booting a device once per worker, not per test, is what keeps suites fast. While a worker starts cold, its first test's timeout is temporarily extended so emulator/simulator boot or WebDriverAgent builds do not eat into the test's own timeout budget; once the worker is ready, the test still gets its full configured timeout. - **Per test:** the app is isolated: the SDK session is closed, the app is terminated if it was launched, mock handlers and recorded requests are reset, key and log buffers are cleared. Each test calls `app.launch()` itself. - **Serial blocks share one app.** Tests in a `test.describe.serial` block run in order on the same app: no isolation between them, so step 2 continues where step 1 left off. The next test outside the block is isolated again. ```ts run import { test } from '@toets/test'; test.describe.serial('onboarding', () => { test('pick a profile', async ({ app }) => { await app.launch(); /* ... */ }); test('then the home screen', async ({ app }) => { /* app is still running */ }); }); ``` ## Principles - **Launch explicitly.** `app.launch({ state, flags, clearData, deepLink })` makes the starting point visible in the test. `app.openDeepLink(url)` delivers a link to the running app ([deep links](/reference/core/docs/deep-links)). - **What `app` holds:** locators (`getByTestId`, `getByText`), `remote`, `focus`, `keyboard` ([text input](/reference/core/docs/text-input)), `media`, `network` and `platform`. - **Platform escape hatch.** `app.platformOnly('web', async (page) => { ... })` runs code with the driver's native handle (a Playwright `Page` on web) only on that platform, as a recorded step. Use it sparingly; it is not portable. ## TV trap: app state survives terminate Terminating a TV app keeps its data: login, profile choice, onboarding flags. Use `launch({ clearData: true })` or `app.reset()` when a test needs a first-run experience. --- # Config Source: https://yusufyildirim.github.io/toets/reference/test/docs/config.md A toets suite is a Playwright Test suite with one project per platform. `defineConfig` and `platforms.*` from `@toets/test` build it. ```ts // playwright.config.ts import { defineConfig, platforms, Key } from '@toets/test'; export default defineConfig({ testDir: 'e2e', app: { web: { url: 'http://localhost:8080' }, androidTV: { apk: 'build/app.apk', package: 'com.example.tv' }, tvOS: { app: 'build/App.app', bundleId: 'com.example.tv' }, }, toets: { sdk: true, mock: true }, projects: [ platforms.web(), platforms.androidTV({ model: 'tv_1080p', osVersion: '34' }), platforms.tvOS({ toets: { keyOverrides: { FAST_FORWARD: { as: Key.RIGHT, holdMs: 800 } } } }), ], }); ``` ## Principles - **Everything Playwright stays Playwright.** `workers`, `retries`, `reporter`, `grep`, `expect.timeout`, UI mode and sharding work unchanged. - **One project per platform.** A project name defaults to the platform (`web`, `android-tv`, `tvos`); add more projects for more devices of one platform. - **Drivers load lazily by package name**: `@toets/driver-web`, `@toets/driver-android-tv`, `@toets/driver-tvos`. Install only the ones you use. `driver` overrides the module (a package or a path relative to the config file). - **One flat options object per project.** `platforms.androidTV({ ... })` takes Playwright project fields (`name`, `retries`, `use`, ...), toets's keys (`driver`, `app`, `model`, `osVersion`, `devices`, `toets`) and the driver's options (e.g. `remote: 'fire-tv'`), typed by the driver package. A custom driver passes its type: `platforms.web({ driver: './my-driver.ts', ... })`. - **Every config type is exported** from `@toets/test`, driver option types included (`WebDriverOptions`, `AndroidTvDriverOptions`, `TvosAppConfig`, ...), so a config can be factored into typed pieces without importing driver packages. - **`model` and `osVersion`** tell the device provider what to boot or lease, e.g. `model: 'tv_1080p', osVersion: '34'`. - **`keyboards`** declares the app-drawn keyboards ([text input](/reference/core/docs/text-input)): top level, per project (`platforms.web({ keyboards })`) or per test (`test.use({ keyboards })`). Each level replaces the one above, never merges. Keep the definitions in a file that imports only `defineKeyboard`: the config loads it. - **Deep links** keep one canonical URL in tests; each platform's form (a web path, a Fire TV intent) is the `deepLink` mapper in its `app` config or a project's `app` ([deep links](/reference/core/docs/deep-links)). - **Relative app paths** (`apk`, `app`) resolve against the config file's directory. - **Options merge** from the top-level `toets` into each project's `toets`. The `app` entry for the platform merges with the project's `app`. - **Snapshot baselines are per project, not per host.** toets projects default `snapshotPathTemplate` to Playwright's default without the host OS suffix; a top-level or project `snapshotPathTemplate` wins. - **The parity reporter is added** after your reporters; `parityReport: false` turns it off. Without a `reporter`, toets uses `list` (`dot` in CI) and `html` (`open: 'never'`), so `npx playwright show-report` works. | `toets` option | Meaning | | -------------- | ------------------------------------------------------------------------------------ | | `sdk` | Wait for the in-app SDK on launch (adds idle sync, app focus, media, launch states). | | `mock` | Run a host-side mock server per worker (`network.mock`): `true` or its settings. | | `keyOverrides` | How a semantic key is performed for this app. Flagged in reports. | | `timeouts` | `actionMs`, `sdkConnectMs`, `navigationSettleMs`. Assertions use `expect.timeout`. | | `remote` | `intervalMs` between `repeat`/`sequence` presses (100), `longPressMs` (1000). | | `idle` | `quietMs`, `budgetMs`: how long assertions wait for idle before polling. | | `steps` | Attach a screenshot and/or text snapshot after every action (costly on devices). | | `video` | `off`, `on`, `retain-on-failure`, where the driver supports `video`. | ## TV trap: one worker per device Each worker drives one device. `workers` above the number of devices you can run (emulators are heavy; tvOS simulators need a Mac each) makes workers wait for or fail to get a device. Start with `workers: 1` on device projects. --- # Devices Source: https://yusufyildirim.github.io/toets/reference/test/docs/devices.md Device platforms need a device per worker. A project picks how it gets one with `devices`; web needs none. ```ts import { platforms } from '@toets/test'; platforms.androidTV({ devices: 'managed', model: 'tv_1080p', osVersion: '34' }); platforms.androidTV({ devices: { mode: 'external', addresses: ['emulator-5554', 'emulator-5556'] }, }); platforms.tvOS({ devices: { mode: 'command', acquire: './scripts/lease-sim.sh', release: './scripts/release-sim.sh', }, }); ``` | Mode | Who provides the device | | ---------- | ----------------------------------------------------------------------------------------------------------------------- | | `managed` | The driver creates, boots, snapshots and resets emulators or simulators. Default when the driver supports it. | | `external` | Already running devices, from `addresses` or `TOETS_DEVICES=emulator-5554,emulator-5556`. Worker slot n uses address n. | | `command` | Your shell commands lease and release devices (device farms, lease brokers). | ## The command contract - `acquire` gets `TOETS_PLATFORM`, `TOETS_WORKER_INDEX`, `TOETS_PARALLEL_INDEX` and `TOETS_DEVICE_SPEC` (JSON), and prints JSON on its last stdout line: `{ "address": "emulator-5554", "id"?: "...", "meta"?: { ... }, "environment"?: { ... } }`. `environment` holds variables the device must be driven with (e.g. a lease broker's `ANDROID_ADB_SERVER_PORT` or `SIMLOCK_IOS_DEVICE_SET`); it lands in `meta.environment` and drivers apply it. - `release` gets the same variables plus `TOETS_DEVICE_ID`, `TOETS_DEVICE_ADDRESS` and `TOETS_DEVICE_META`. - Timeouts: `acquireTimeoutMs` (default 10 minutes, boots are slow) and `releaseTimeoutMs` (2 minutes). ## Principles - **One device per worker, held for the worker's life.** The lease is released when the worker exits, including after failures. - **`TOETS_PARALLEL_INDEX` is the stable slot** (`0..workers-1`), kept when Playwright replaces a crashed worker. Use it, not the worker index, to pick an exclusive device. - **Fewer devices than workers fails fast** with `NOT_ENOUGH_DEVICES` instead of sharing a device between workers. ## TV trap: emulators need KVM, simulators need macOS Android TV emulators need hardware acceleration (KVM on Linux CI). tvOS simulators run only on macOS. Plan CI runners per platform and keep device projects separate so they can run on different machines. --- # Reporting Source: https://yusufyildirim.github.io/toets/reference/test/docs/reporting.md toets reports through Playwright: every action is a step, artifacts are attachments, and a parity matrix shows which test ran where. ```text toets parity (10 tests): web: 10 passed; tvos: 6 passed, 4 skipped differs: navigation.spec.ts > color keys work: web passed, tvos skipped (requires key.color: not available on tvos) Parity matrix: toets-report/parity.md ``` ## Steps and attachments - **Steps:** `launch`, `press SELECT`, `pressUntilFocused RIGHT getByTestId('rail-0-card-2')`, `repeat RIGHT x3`, `platformOnly web`. Overridden keys read `press FAST_FORWARD (override: hold RIGHT 800ms)`. - **On failure:** `toets-failure` (the [failure dump](/reference/core/docs/failure-dumps)) and `toets-screenshot`. - **Always, when present:** `toets-logs` (app and driver logs) and `toets-network.har` (the test's mock server traffic as HAR 1.2, failed requests included). - **Optional per step:** `steps: { screenshot: true, snapshot: true }` attaches the screen after every action. - **Video:** `video: 'on' | 'retain-on-failure'` attaches `toets-video` where the driver supports `video`. ## Parity matrix Written to `toets-report/parity.md` and `parity.json` next to the config after every run, one row per test and one column per toets project: ```md | Test | web | tvos | | --------------------------------- | ------ | --------------------------------------------------- | | navigation.spec.ts > color keys | passed | skipped (requires key.color: not available on tvos) | | navigation.spec.ts > fast forward | passed | passed [overrides: FAST_FORWARD = hold RIGHT 800ms] | ``` Configure with `parityReport: { outputFile, summary }` (`outputFile` is relative to the config file, like Playwright reporter paths) or turn it off with `parityReport: false`. ## Principles - **Parity is a first-class result.** A suite that is green everywhere but skips half its tests on one platform is not done; the matrix makes that visible. - **Overrides are flagged, not hidden.** A test that only passes because a key is performed differently says so. ## TV trap: `--reporter` replaces the config's reporters Passing `--reporter=list` on the command line replaces every configured reporter, including the parity reporter. Configure reporters in the config file instead. --- # requires Source: https://yusufyildirim.github.io/toets/reference/test/docs/requires.md `requires(...capabilities)` declares what a test needs. On a platform without it, the test is skipped with the reason instead of failing, and the parity report shows where and why. ```ts run import { test, expect, requires, Key } from '@toets/test'; test('green key opens the guide', requires('key.color'), async ({ app }) => { await app.launch(); await app.remote.press(Key.GREEN); await expect(app.getByTestId('guide')).toBeVisible(); }); test.describe('player', requires('media.state'), () => { test('toggles playback', async ({ app }) => { /* ... */ }); }); test('tagged', { ...requires('key.numeric'), tag: '@smoke' }, async ({ app }) => { /* ... */ }); ``` ## Principles - **It is a Playwright annotation** (`{ type: 'requires' }`), so it works on tests and `describe` blocks and keeps test locations, UI mode and reporters intact. - **Skip reason format:** `requires key.color: not available on tvos`; when only a toets option is missing: `requires media.state: not available on web (toets.sdk off)`. - **The check is against declared capabilities:** the driver's, plus SDK capabilities when `sdk` is on (the app connects only at launch), plus `network.mock` when `mock` is on. - **Declare what the test uses, not the platform it targets.** `requires('key.color')` stays correct when a new platform gains color keys; skipping on `tvos` does not. ## TV trap: overrides are not requirements A key override (`FAST_FORWARD` performed as a long `RIGHT`) means the app supports the action differently, so the test runs, and the parity report flags it. Use `requires` only when the platform truly cannot do it. --- # Assertions Source: https://yusufyildirim.github.io/toets/reference/core/docs/assertions.md Every toets matcher retries until it passes or the timeout elapses (`expect.timeout`, default 5000 ms). There are no sleeps in a toets test. ```ts nocheck await app.remote.press(Key.SELECT); await expect(app.getByTestId('details-title')).toHaveText('The Matrix'); await expect(app.getByTestId('play')).toBeFocused({ timeout: 10_000 }); ``` | Subject | Matchers | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Locator | `toBeVisible`, `toBeInViewport`, `toBeFocused`, `toHaveFocusWithin`, `toBeEnabled`, `toBeDisabled`, `toBeSelected`, `toBeBusy`, `toHaveText`, `toContainText`, `toHaveCount` | | App, Locator | `toMatchTextSnapshot`, `toMatchScreenshot` | | `app.media` | `toBePlaying`, `toBePaused`, `toHaveMediaState`, `toHavePosition` (needs `media.state`) | | `app.network` | `toHaveRequested(filter, { times? })` (needs `network.mock`) | | Locator | `toHaveValue(text \| RegExp)`: system text fields ([text input](/reference/core/docs/text-input)) | | `app.keyboard` | `toBeOpen()`: a keyboard is open ([text input](/reference/core/docs/text-input)) | ## Principles - **Assert focus, not just visibility.** On a TV the question is almost always "where is focus?". `toBeFocused` and `toHaveFocusWithin` (focus is on the element or a descendant) are the core TV assertions. - **`.not` waits too.** `expect(x).not.toBeVisible()` passes as soon as the element is gone, and fails only after the timeout. - **Missing elements:** `toBeVisible` and `toBeInViewport` treat a missing element as "not visible". The other locator matchers wait for the element and fail if it never appears, with or without `.not`. - **Failures explain themselves:** the message shows the locator, expected and received values, what was focused, how many checks ran, and whether the app was idle (see [idle](/reference/core/docs/idle)). ## TV trap: visible is not in viewport Offscreen rail items are often laid out and "visible" in the tree but scrolled out of the screen. Use `toBeInViewport` when you mean "the user can see it". --- # Capabilities Source: https://yusufyildirim.github.io/toets/reference/core/docs/capabilities.md A capability is something a target can do: press color keys (`key.color`), report media state (`media.state`), mock the network (`network.mock`). The available set is the driver's capabilities, plus the SDK's when the app embeds it, plus `network.mock` when mocking is on. ```ts nocheck test('the guide opens with the green key', requires('key.color'), async ({ app }) => { await app.launch(); await app.remote.press(Key.GREEN); await expect(app.getByTestId('guide')).toBeVisible(); }); if (app.platform.has('media.state')) { /* optional extra checks */ } ``` ## Principles - **Declare, do not branch.** `requires(...)` skips the test with a reason on platforms without the capability, and the parity report shows where and why. A test that branches on `app.platform.name` hides gaps. - **Using a missing capability fails loudly** with `CAPABILITY_MISSING` or `KEY_UNSUPPORTED`, naming the capability and how to declare it. - **SDK capabilities** (`tree.hierarchy`, `sync.idle`, `media.state`, `app.state`, `logs`) count as available for `requires` when the SDK is configured, because the app connects only at launch. ## TV trap: same key, different remotes Android TV remotes vary by vendor; the Siri Remote has no color, numeric or channel keys. A suite that passes on one remote can be untestable on another. Capabilities make that visible instead of turning it into failures. --- # Deep links Source: https://yusufyildirim.github.io/toets/reference/core/docs/deep-links.md `app.launch({ deepLink })` starts the app from a link; `app.openDeepLink(url)` delivers a link to the running app. Tests pass one canonical absolute URL; each driver's `deepLink` mapper translates it to the platform's form. Concepts and traps: the `concepts/deep-links` page of the docs site. ```ts nocheck await app.launch({ deepLink: 'myapp://details/42' }); await app.launch({ deepLink: 'myapp://details/42', state: 'signed-in', clearData: true }); await app.openDeepLink('myapp://details/43'); ``` ## API | Call | Capability | Does | | -------------------------------------- | ----------------- | ---------------------------------------------------------------------------------------- | | `app.launch({ deepLink, ...options })` | `deeplink.launch` | Stops the app (and clears its data with `clearData`), then starts it from the link. | | `app.openDeepLink(url)` | `deeplink.open` | Delivers the link to the running app. Fails with `APP_NOT_LAUNCHED` before `app.launch`. | The link is translated once per call, before the app is touched: an invalid link or a throwing mapper fails the step with `DEEPLINK_INVALID` and leaves the app as it was. ## Mappers `type DeepLinkMapper = (link: URL) => T`, set as `deepLink` in a platform's app config (`app.web`, `app.androidTV`, `app.tvOS`) or a project's `app`: | Driver | `T` | Default | | ---------- | --------------------------- | ---------------------------------------------------------------------------------- | | web | `string` | `myapp://details/42?t=1` → `details/42?t=1`; `https://x.com/watch/42` → `watch/42` | | Android TV | `string \| AndroidDeepLink` | the link as a `VIEW` intent | | tvOS | `string` | the link | Web resolves the result against the app `url` like a link on its page (`details/42` keeps the `url` path, `/details/42` replaces it); it must end up http(s) or file. tvOS needs an absolute URL. Android takes a URI or an intent: ```ts nocheck interface AndroidDeepLink { uri?: string; // -d action?: string; // -a, default android.intent.action.VIEW categories?: string[]; // -c mimeType?: string; // -t extras?: Record; // --es, --ez, --ei (--el beyond 32 bits, up to 2^53), --ef } ``` ## Per platform **Web.** Browsers have no OS deep links. A deep link launch loads the translated page URL instead of `url`, with the launch payload in an init script (`window.__TOETS__`), never in the link's URL. A page that answers an HTTP error fails with `DEEPLINK_UNHANDLED`: serve the app on every route (SPA history fallback) or map the link to a URL the server serves. No `deeplink.open`. **Android TV.** `am start -W` with the intent and `-p `, never a component: the OS picks the activity from the app's intent filters, as for a real link. A deep link launch force-stops the app first (and clears its data with `clearData`) and adds the launch payload extra `__toets`; `openDeepLink` sends the same intent without either, so a running app gets it in `onNewIntent`. No resolving activity: `DEEPLINK_UNHANDLED`. **tvOS.** The URL is opened in the app through XCTest (`XCUIApplication.open`); `simctl openurl` would stop at a system "Open in ...?" prompt. A deep link launch can not pass launch arguments, so the launch payload goes into the app's user defaults (`defaults write __toets`), where `UserDefaults.standard.string(forKey: "__toets")` and the SDK read it like the argument; toets removes it again on the next launch, terminate or stop. `launchArguments` and `launchEnvironment` do not apply to deep link launches. A URL whose scheme the app does not register in its Info.plist (`CFBundleURLTypes`) fails with `DEEPLINK_UNHANDLED`. Universal links (https) are not supported. ## Reports Step titles and failure dumps show the link and, when it differs, its translation: ```text launch (deepLink: myapp://details/42 → intent com.example.PLAY extras { contentId: "42" }) openDeepLink myapp://details/42 → http://localhost:8080/watch/42 ``` The failure dump lists the `last launch` and `last deep link` of the test. ## Errors | Code | When | | -------------------- | ---------------------------------------------------------------------------------------------------------------- | | `DEEPLINK_INVALID` | The link is not an absolute URL, or the platform's mapper threw or returned something the platform can not open. | | `DEEPLINK_UNHANDLED` | No activity, URL scheme or page of the app handles the translated link. | | `APP_NOT_LAUNCHED` | `openDeepLink` before `app.launch`. | | `CAPABILITY_MISSING` | The platform lacks `deeplink.launch` or `deeplink.open`: declare it with `requires`. | With a deep link launch, `SDK_NOT_CONNECTED` also points at Android trampoline activities that start the real activity without forwarding the extras. --- # Writing a driver Source: https://yusufyildirim.github.io/toets/reference/core/docs/drivers.md A driver connects toets to one platform. It is a package whose default export is a `DriverModule`; `@toets/test` imports it by name only when a project uses it. ```ts nocheck import type { DriverModule } from '@toets/core'; const module: DriverModule = { platform: 'android-tv', async createDriver(options, ctx) { return new AndroidTvDriver(options, ctx.app, ctx.device); }, createDeviceProvider: (options) => new EmulatorProvider(options), // for `managed` devices }; export default module; ``` ## Contract - **Small and dumb.** A driver answers `query`, `focused`, `tree`, `press`, `launch`, `screenshot` and declares its `capabilities`. It never claims `network.mock` (the core grants it when the mock server is on) or SDK capabilities. Retries, strictness, matchers, navigation, idle and reporting live in core, so every platform behaves the same. - **Selector semantics are shared.** Answer `query` with `evaluateChain` (and `focused` with `focusedIn`) from `@toets/core` over your tree instead of reimplementing them: the first step searches the whole tree, text matches the deepest element (`matchText`), regexes are stateless (`testRegExp`), `nth` picks among the current matches. A driver that must evaluate elsewhere for speed (the web driver evaluates in the page) keeps exactly these semantics. - **Stable refs.** `ElementSnapshot.ref` must be the same for one element across `query`, `focused` and `tree`, and stay stable while the element is attached. Focus navigation and `focus.current()` compare refs. - **One coordinate space.** Bounds and `UITree.viewport` share the tree's coordinate space (points, dp or CSS pixels), with the viewport origin at 0,0. The viewport screenshot may be in device pixels; core scales by image width over viewport width when it crops elements and masks. - **Launch passes the payload** (`sdkUrl`, `token`, `mockUrl`, `state`, `flags`) to the app in the platform's way (URL parameter, intent extra, launch arguments), always encoded with `encodeLaunchPayloadParam` from `@toets/protocol` (base64url JSON). - **Deep links.** A driver that declares `deeplink.launch` provides `deepLinks` (`DriverDeepLinks`): `translate(link)` turns the canonical URL into the platform's form through the user's `deepLink` mapper (`DeepLinkMapper`), with a one-line `description` for reports; `launch({ deepLink })` starts the app from it, through the OS so its routing is tested; `open(link)` (with `deeplink.open`) delivers it to the running app. Fail with `DEEPLINK_INVALID` for a mapper result the platform can not open and `DEEPLINK_UNHANDLED` when the app does not handle it. - **Text entry.** A driver that declares `text.input` provides `text` (`DriverTextInput`): replace, insert, delete backward, submit and close, through the platform's own text entry, into the focused field (the core passes the field as it sees it, `value` included). The core moves focus there with real presses, verifies the result and closes a keyboard `fill` opened. Report fields as `editable` with their `value`, masked (one `•` per character) and `secure` for passwords. Never inject text through the SDK. - **Devices:** use `DeviceAcquireOptions.parallelIndex` to pick an exclusive device per worker slot. - **Errors** are `ToetsError` with a `hint` and a `docs` slug. ## Runners `@toets/core/runner` brings a target up and down for a runner: `RunningTarget.start` loads the driver module, picks the device provider (`managed`, `external`, `command`), leases a device, starts the driver, the mock server and the SDK host, and builds the `AppRuntime`. `@toets/test` (per worker) and `@toets/mcp` (per session) both use it, so a target behaves the same in tests and in agent exploration. It also has the small helpers interactive runners need to report like tests: `settleFocus` (wait for a press to land, as `navigateTo` does), `jsString` and `describeKeyOverride`. ## Testing a driver `@toets/core/testing` has `FakeDriver` (a scripted screen with geometry-based focus), `FakeSdkHost` and `FakeMockServer`. Run the core behaviour against the fake, and keep real-device tests for the mapping your driver owns. ## TV trap: focus is not keyboard focus On Android TV and tvOS the focused element comes from the platform's focus engine, not from accessibility focus. Read the real focus state (`focused` attribute, `hasFocus`), and never move focus with taps or accessibility actions. --- # Failure dumps Source: https://yusufyildirim.github.io/toets/reference/core/docs/failure-dumps.md When a test fails, toets writes a `toets-failure.md` dump and a `toets-screenshot.png` to the test's output folder (`test-results//`) and attaches both to the Playwright report; the console prints their paths. The dump is everything needed to understand the failure without rerunning it: ````md # toets failure dump - platform: android-tv - capabilities: key.back, key.color, key.media.toggle - sdk: off (black-box) - focused: card_1 "Movie 1" - keyboard: none - last keys: RIGHT, RIGHT, SELECT ## Screen ```yaml - rail: - card_1 "Movie 1" [focused] - card_2 "Movie 2" ``` ```` It also lists busy resources (when idle sync is on), recent app logs and recorded requests. ## Principles - **Launch and deep link.** `last launch` and `last deep link` repeat the test's last `launch` and `openDeepLink` steps with the link's translation (`myapp://details/42 → intent com.example.PLAY ...`), so a link that landed on the wrong screen shows what the platform really opened ([deep links](/reference/core/docs/deep-links)). - **Keyboard state.** The `keyboard` line names the open keyboard: a declared one with its layer (`search (layer: digits)`), `system`, or `none`. A test stuck behind an open keyboard shows here first ([text input](/reference/core/docs/text-input)). - **Text first.** The screen is a [text snapshot](/reference/core/docs/text-snapshots), readable in CI logs and by AI agents. The screenshot is attached separately. - **Never masks the real error.** Collecting the dump never throws; missing parts are left out. - **Logs and network traffic** are attached for every test (`toets-logs`, `toets-network.har`), not only failures. - **Failed requests stay.** The dump lists the last 20 requests plus any earlier failed ones (no route, upstream unreachable), with the failure reason. ## TV trap: the failing key was three presses ago On a TV the assertion that fails is often far from the press that went wrong. The last keys and the focused element usually tell you which press moved focus somewhere unexpected. --- # Focus navigation Source: https://yusufyildirim.github.io/toets/reference/core/docs/focus-navigation.md Moving focus with real D-pad presses, without hardcoding `DOWN, DOWN, RIGHT`, which breaks whenever the layout changes. toets never models the app's focus graph; the focused element is the only focus input it reads. Every press is checked by reading focus again. ```ts nocheck await app.focus.pressUntilFocused(Key.DOWN, app.getByTestId('rail-popular')); await app.focus.pressUntilFocused(Key.RIGHT, app.getByTestId('card-7')); await app.remote.press(Key.SELECT); await app.focus.navigateTo(app.getByTestId('menu-watchlist')); await app.focus.waitForChange(() => app.remote.press(Key.BACK)); ``` ## `pressUntilFocused(key, target, { maxPresses })` Presses one direction key (`UP`, `DOWN`, `LEFT`, `RIGHT`) until `target` or an element inside it holds focus, and returns the number of presses (0 when it already does). A target that is not focusable itself also counts once the element around it holds focus: `getByText('Allow')` names the label inside a button, because text belongs to the deepest element, and the button is what takes focus. The same goes for `navigateTo`. Matchers stay exact: `toBeFocused()` on the label fails, assert focus on the button. 1. Read focus. Done when the target (at most one match) is focused or has focus within. 2. Press `key`. Wait until focus lands on another element, up to `navigationSettleMs` (default 1000; SDK idle ends the wait early once the app is done). 3. Repeat, failing fast: | Code | When | Usual cause | | ------------------- | ---------------------------------------------------------- | ------------------------------------------------------------ | | `FOCUS_STUCK` | A press did not move focus within `navigationSettleMs`. | End of a row or list, a focus trap, a disabled target. | | `FOCUS_LOOP` | Focus came back to an element it already left. | A wrap-around row or menu: the target is not on this path. | | `FOCUS_UNREACHABLE` | `maxPresses` (default 50) presses without reaching target. | The target is further away (raise it) or elsewhere. | | `NO_FOCUS` | Nothing holds focus, before the first press or after one. | The app is not ready, or a press moved focus out of the app. | Every message lists the elements focus passed through. The target does not need to exist at the start: items of virtualized lists appear as focus approaches, and each press re-reads the screen. An element counts as the same when its ref, test ID and text match. Some drivers derive refs from tree positions, so a list that scrolls under a fixed focus position keeps the ref while the focused item changes. When an editable text field holds focus and the first `UP` or `DOWN` press does not move focus (for example, Android `EditText` moving the caret to the start or end of the line), both `pressUntilFocused` and `navigateTo` press the same direction once more before treating focus as stuck. `LEFT` and `RIGHT` are not retried because they move the caret character-by-character. ## `navigateTo(target, { maxPresses })` For targets that are not one direction away. Returns the directions pressed. 1. Aim: directions toward the target's bounds first (same row: horizontal; same column: vertical; otherwise vertical, then horizontal), then detours. 2. Press, then read focus. Every observed move is learned, including presses that did not move focus. A direction is never tried twice from the same element; known moves lead back to elements with untried directions. 3. Stop when the target holds focus, or fail with `FOCUS_UNREACHABLE` when no direction is left or after `maxPresses` (default 50), with the path tried. The target must be on screen, since its bounds aim the presses. For items that appear only as focus comes near, use `pressUntilFocused`. ## Principles - **Real presses only.** Focus is never set programmatically, so the test proves a user can get there. - **Observe, never predict.** The app's focus engine decides where a press goes; toets checks where focus landed and reacts. - **`waitForChange`** runs an action and waits until focus lands on a different element. Use it when the destination is not known, for example after `BACK`. ## TV trap: focus memory and traps TV focus engines remember the last focused child of a row and may jump there instead of the nearest item. Modals trap focus. Both look like "geometry lies". `pressUntilFocused` does not care where a press should go, only where it went; `navigateTo` copes by learning the real moves. A stuck or unreachable error usually means a real focus trap in the app. --- # Idle sync Source: https://yusufyildirim.github.io/toets/reference/core/docs/idle.md With the in-app SDK connected (`sync.idle`), the app reports when it is idle: no pending network, animations, short timers or focus transitions for about 100 ms. Assertions wait for idle before checking, so they check a settled screen and negative assertions resolve quickly. ```ts // playwright.config.ts import { defineConfig } from '@toets/test'; export default defineConfig({ toets: { sdk: true, idle: { quietMs: 100, budgetMs: 2000 } }, // ... }); ``` ## Principles - **Idle is an accelerator, never a gate.** Every assertion still retries until its timeout. Without the SDK, or when the app never goes idle, toets polls instead. A test never fails only because the app was busy. - **Busy is reported.** When an assertion fails and the app never became idle within `budgetMs`, the failure names what kept it busy, for example `app never became idle within 2000ms (busy: network GET /api/home); polled instead`. - **Navigation settles on idle too.** `focus.pressUntilFocused` and `focus.navigateTo` wait for idle (or a short focus poll) between presses. ## TV trap: things that never stop Autoplaying hero trailers, clocks and polling requests keep an app busy forever. Exclude them as noise in the SDK, or accept that assertions on those screens fall back to polling. Mark long custom work busy with the SDK's `markBusy()` so assertions wait for it. --- # Locators Source: https://yusufyildirim.github.io/toets/reference/core/docs/locators.md A locator describes how to find an element, not the element itself. It is resolved again on every action and assertion, so it never goes stale when the screen re-renders. ```ts nocheck const rail = app.getByTestId('rail-popular'); const card = rail.getByText(/the matrix/i).first(); await app.focus.pressUntilFocused(Key.RIGHT, card); await expect(card).toBeFocused(); ``` ## Principles - **Prefer test IDs.** `getByTestId` maps to `data-testid` (web), resource ID (Android) and accessibility identifier (tvOS). Text changes with locale and copy edits. - **Chains narrow.** Each step searches inside the previous matches. The first step searches the whole screen, root included. - **Text matching:** a string is a case-insensitive substring after whitespace normalization; `{ exact: true }` is a case-sensitive full match; a `RegExp` is tested as is. Text matches resolve to the deepest element that carries the text. - **Strict by default.** Actions and single-element assertions fail when a locator matches more than one element. Add `.first()`, `.nth(i)` or a narrower chain. `toHaveCount` and `count()` accept many. - **`app.focus.current()`** is a locator for whatever is focused right now. - **The one action is `fill(text)`**: it replaces a field's text through its keyboard, reaching the field with real presses ([text input](/reference/core/docs/text-input)). Everything else is focus and keys; there is no click. ## TV trap: virtualized lists TV rails and grids render only the items near focus. An item ten cards to the right does not exist yet, so `getByTestId('rail-0-card-10')` finds nothing. Press toward it: `app.focus.pressUntilFocused(Key.RIGHT, card)` works before the card exists, re-reading the screen after every press. --- # Network mocking Source: https://yusufyildirim.github.io/toets/reference/core/docs/network.md With `toets: { mock: true }`, a host-side mock server runs per worker. The app learns its address (`mockUrl`) from the launch payload and sends API traffic there; handlers decide what to answer and everything else is proxied upstream. No certificates, no device proxy settings, same on every platform. ```ts nocheck import { http, HttpResponse } from '@toets/test'; app.network.use(http.get('*/v1/rails', () => HttpResponse.json([]))); await app.launch(); await expect(app.getByTestId('rails-empty')).toBeVisible(); await expect(app.network).toHaveRequested({ method: 'GET', url: '/v1/rails' }, { times: 1 }); ``` ## Principles - **Cooperative, not intercepting.** The app must route requests to `mockUrl` when it is present. This is a few lines in the app's HTTP client, and it is what makes mocking portable. - **Handlers are MSW handlers.** Use them before `launch()` for data the first screen loads. - **Baseline handlers come from config**: `toets: { mock: { handlers: [...] } }` applies them in every test, below the per-test ones. The other `mock` settings: `onUnhandledRequest` (`proxy` or `reject`), `port`, `maxRecordedBodyBytes`. - **Isolation:** handlers added in a test and recorded requests are reset between tests; a serial block keeps its handlers. - **Recorded requests** are attached to the test report and summarized in failure dumps. ## TV trap: requests that bypass the client Players fetch manifests and segments through native media stacks, and images load through native image loaders. Those requests do not go through the app's HTTP client, so they are not mocked unless the app routes them too. --- # Remote Source: https://yusufyildirim.github.io/toets/reference/core/docs/remote.md `app.remote` sends real key events, the same way a user's remote does. Keys are semantic (`Key.SELECT`, `Key.BACK`, `Key.PLAY_PAUSE`); each driver maps them to its platform. ```ts nocheck await app.remote.press(Key.DOWN); await app.remote.repeat(Key.RIGHT, 3); await app.remote.sequence([Key.DOWN, Key.SELECT]); await app.remote.longPress(Key.SELECT, 800); ``` ## Principles - **Capabilities, not platform checks.** D-pad and `SELECT` work everywhere. Other keys need a capability (`BACK` needs `key.back`, color keys need `key.color`, ...). Pressing an unsupported key fails with `KEY_UNSUPPORTED`; `repeat` and `sequence` check every key before the first press, so they never stop half-way. Declare it with `requires('key.color')` so the test is skipped on platforms without it. - **Key overrides describe the app, not the platform.** When an app maps a semantic key to another gesture, configure it once instead of branching in tests: ```ts nocheck toets: { keyOverrides: { FAST_FORWARD: { as: Key.RIGHT, holdMs: 800 } } } ``` The step reads `press FAST_FORWARD (override: hold RIGHT 800ms)` and the parity report flags the test, so overrides never hide silently. - **Every press is a step** in the Playwright report, and the last keys appear in failure dumps. ## TV trap: tvOS has no BACK The Siri Remote's back button is `MENU`, and there are no color or numeric keys. Write `Key.BACK` and let the tvOS driver map it, or override it for your app; do not branch on the platform. --- # Screenshots Source: https://yusufyildirim.github.io/toets/reference/core/docs/screenshots.md ```ts nocheck await expect(app).toMatchScreenshot({ mask: [app.getByTestId('hero-video')] }); await expect(app.getByTestId('rail')).toMatchScreenshot({ maxDiffPixelRatio: 0.01 }); const shot = await app.screenshot(); // opaque; screenshotPng(shot) gives the PNG bytes ``` ## Principles - **Baselines are per project, never per host.** Each project (platform and device) has its own baseline files; different platforms render differently and are never compared to each other. A missing baseline is written and the test fails once (Playwright's `toMatchSnapshot`); update with `--update-snapshots`. toets projects default `snapshotPathTemplate` to Playwright's default without the host OS suffix (`{snapshotDir}/{testFileDir}/{testFileName}-snapshots/{arg}{-projectName}{ext}`), so a baseline recorded on a laptop is the one CI compares to. Set `snapshotPathTemplate` to change it. - **Stable before compared.** `toMatchScreenshot` waits until two consecutive screenshots are identical, then compares with Playwright's image comparator (`threshold`, `maxDiffPixels`, `maxDiffPixelRatio`). - **Mask what moves.** `mask` paints the given elements a solid color before comparing. - **Element screenshots are crops** of the full screen on every platform, so they look the same everywhere. An element that is not on screen fails with `ELEMENT_OFFSCREEN`. - **Prefer text snapshots** for structure and state; use screenshots for what only pixels show (focus rings, layout, artwork). ## TV trap: video and focus animations A playing video, a focus scale animation or a shimmer placeholder never produces two identical frames, so the assertion times out with "the screen kept changing". Mask the video surface, assert after the focus animation settles, or assert a region that does not move. ## Web trap: the browser renders with the host's fonts Emulator and simulator screenshots come from the device and do not depend on the host. Chromium does: fonts and anti-aliasing differ between macOS and Linux. Record web baselines in the environment CI runs (for example Playwright's Docker image), or keep web screenshot assertions to regions without text. --- # In-app SDK Source: https://yusufyildirim.github.io/toets/reference/core/docs/sdk.md The SDK is an optional library inside the app. It connects back to the test host when the app is launched by toets and answers questions only the app can answer quickly: the element tree, focus, idle state, media state, app state and logs. ```ts nocheck // playwright.config.ts export default defineConfig({ toets: { sdk: true } /* ... */ }); // a test await app.launch({ state: 'details:the-matrix' }); // needs app.state await expect(app.media).toBePlaying(); // needs media.state ``` ## How it fits - **On launch** toets issues a launch token and passes a payload (`sdkUrl`, `token`, `mockUrl`, `state`, `flags`) to the app through the driver. The app connects and toets waits up to `timeouts.sdkConnectMs`; if it never connects, launch fails with `SDK_NOT_CONNECTED`. - **Reloads keep the launch.** When the app reloads (`location.reload()`, a React Native JS reload or restart), its session closes and the new JS context connects again with the same token. toets attaches the new session; reads meanwhile wait for it, up to `timeouts.sdkConnectMs`, and fall back to the driver if it never comes. The next `launch`, `terminate` or `reset` ends the launch and revokes the token. - **Composition:** the SDK answers tree, queries, focus, media and idle; the driver still does input, launch and screenshots. If an SDK request fails, toets falls back to the driver. When the SDK reports nothing focused, the driver's focused element counts, matched into the SDK tree by its unique test ID: some native views take focus without a framework focus event (a react-native-tvos `TextInput` on tvOS). - **Without the payload the SDK is inert**, so production builds can ship it. ## Principles - **Black-box first, not black-box only.** Locators, focus, remote, screenshots and mocking work without the SDK. The SDK makes them faster and more reliable; it does not change what a test means. The exception is focus owned by a JS focus engine: only the app knows it, and reports it with `reportFocus()`. - **Launch states replace click-throughs.** `launch({ state })` lets the app jump straight to a screen, so a test about the player does not navigate menus first. ## TV trap: the app is not a browser There is no DOM to inspect on Android TV or tvOS, and native accessibility trees are slow and lossy. The SDK is how a React Native or native app reports focus and idle with the same fidelity as the web. --- # Text input Source: https://yusufyildirim.github.io/toets/reference/core/docs/text-input.md `locator.fill()` and `app.keyboard` put text into fields through a keyboard: the platform's system text entry for system text fields, or an app-drawn keyboard declared with `defineKeyboard()`, typed key by key with the remote. Concepts and traps: the `concepts/text-input` page of the docs site. ```ts nocheck await app.getByTestId('search-input').fill('matrix'); await app.keyboard.type(' 2'); await app.keyboard.erase(2); await app.keyboard.submit(); await expect(app.getByTestId('email')).toHaveValue('ada@example.com'); await expect(app.keyboard).toBeOpen(); await app.getByTestId('pin-value').fill('2580', { mask: true }); ``` ## Declaring app keyboards ```ts nocheck // keyboards.ts: imports only defineKeyboard, so the config can load it. import { defineKeyboard } from '@toets/test'; export const keyboards = [ defineKeyboard({ name: 'search', root: { testId: 'osk' }, fields: [{ testId: 'search-input' }], layers: [{ testId: 'osk-shift' }, { testId: 'osk-symbols' }], space: { testId: 'osk-space' }, backspace: { testId: 'osk-del' }, clear: { testId: 'osk-clear' }, submit: { testId: 'osk-go' }, }), ]; ``` Pass them with `defineConfig({ keyboards })`, `platforms.*({ keyboards })` or `test.use({ keyboards })`. Each level replaces the one above. Names must be unique (`DUPLICATE_KEYBOARD`). Each target is `{ testId?, text?, exact?, nth? }`, the selector chain `getByTestId(testId).getByText(text, { exact }).nth(nth)`. | Field | Resolves from | Meaning | | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `name` | | Shown in step titles, snapshots and errors. | | `root` | screen | The keyboard's container. The keyboard is open while it is visible. | | `fields` | screen | The fields it types into. `fill` on one of them uses this keyboard, opening it with `SELECT` when it is closed. | | `keys` | `root` | Character keys. Default: every focusable element in `root` whose text is one character. Multi-character keys (`.com`) need it. | | `layers` | `root` | Toggles that switch layers (Shift, `?123`, `ABC`). | | `space` | `root` | The space key, when its text is not `' '` (usually `space` or an icon). | | `backspace` | `root` | Deletes one character. `erase()` needs it; `fill` uses it to clear when there is no `clear`. | | `clear` | `root` | Clears the field at once. | | `submit` | `root` | Search, Go, Done. `submit()` needs it. | A key types its text. When `keys` is set, it replaces the default; list the one-character keys too. ## Which keyboard `locator.fill(text)`: 1. A declared keyboard whose `fields` match the field (the field, an element inside it, or the focusable element holding it). Closed: toets moves focus to the field, presses `SELECT`, and waits up to `timeouts.actionMs` for `root`. 2. Else system text entry, when the field is a system text field (`editable` in the snapshot). Needs `text.input`. 3. Else `NO_KEYBOARD`. `app.keyboard`: 1. The declared keyboard holding focus. 2. Else system text entry, when the focused element is a system text field. 3. Else the only declared keyboard on screen. 4. Else `NO_KEYBOARD` (none) or `AMBIGUOUS_KEYBOARD` (several on screen, none focused). ## How text goes in **System text fields.** Focus moves to the field with real D-pad presses, then the driver replaces its text the way the platform's own text entry does. `fill` closes a system keyboard it opened, and checks the value afterwards. | Platform | `fill` | `type` | `erase` | `submit` | | ---------- | ---------------------------------------------------------- | -------------- | ---------------- | ------------------- | | web | select all, CDP `Input.insertText` | `insertText` | `delete` command | `Enter` | | Android TV | UiAutomator2 clear + set text (unicode) | `mobile: type` | `KEYCODE_DEL` | IME action (`done`) | | tvOS | `SELECT` opens, XCUITest clear + `typeText`, `Menu` closes | `typeText` | `typeText('\b')` | `typeText('\n')` | `expect(app.keyboard).toBeOpen()` passes while a declared keyboard's `root` is visible, or while the system keyboard is open: on Android TV the IME is shown, on tvOS the keyboard screen is up, and on web (no on-screen keyboard) a text field holds focus. **App keyboards.** `fill` clears the field first (`clear`, else `backspace` once per character), types, then checks that the field shows exactly the text (`TEXT_NOT_ENTERED` otherwise). For each character, toets: 1. Reads the keyboard from one tree and picks the key: the longest key text that starts the remaining text (`.com` before `.`), or `space` for a space. 2. When no key on the current layer matches, presses the declared `layers` toggles until one does. Layers are not tracked: toets explores the toggles (each one at most once per layer it reaches) and fails with `CHAR_NOT_ON_KEYBOARD`, listing the layers it saw. 3. Plans the walk to the key from the keys' geometry, presses it at once, and checks where focus landed. A missed prediction falls back to step-by-step navigation from there. 4. Presses `SELECT` and waits until the field text (or, for a toggle, the keys) changes. Each key is one `key` step inside the action's step. ## Values and masking The snapshot shows a system field's value, masked when the field is secure. A declared keyboard collapses to one line: its name, its layer (named from its keys: `lower`, `upper`, `mixed`, `digits`, `symbols`) and the focused key. Snapshot the keyboard's root to see the keys. ```yaml - email [editable] value="ada@example.com" - password [editable, secure] value="•••••••••" - 'osk [keyboard: search, layer: lower, focused: "m"]' ``` `toHaveValue` reads system fields only: elsewhere it fails with `NOT_EDITABLE`, and on secure fields with `SECURE_FIELD`. Text typed into an app keyboard's field is its text: use `toHaveText`. `{ mask: true }` (automatic for secure system fields) masks the text in step titles, errors and MCP output. App keyboards do not know a field is secret: pass `mask` for PINs and passwords. ## Reports | Step title | Annotation | | ---------------------------------------------------------- | ----------- | | `fill getByTestId('search-input') "ma" (keyboard: search)` | `9 presses` | | `fill getByTestId('email') "ada@example.com" (system)` | `2 presses` | | `type "••••" (keyboard: pin)` | `7 presses` | | `erase 2 (keyboard: search)`, `submit (system)` | | The press count arrives once the step ends, so it is a `toets` annotation on the step in the HTML report, not part of the title. The failure dump has a `keyboard:` line: the open keyboard, `system`, or `none`. ## Capabilities | Capability | web | Android TV | tvOS | Without it | | ------------ | --- | ---------- | ---- | --------------------------------------------------------------------- | | `text.input` | yes | yes | yes | system text fields fail with `CAPABILITY_MISSING`; app keyboards work | App keyboards need nothing beyond the D-pad and `SELECT`. With the SDK on, the SDK reports `editable`, `value` and `secure` (protocol 1.1). Text never goes through the SDK: it is entered the way users enter it. ## Errors | Code | When | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `NO_KEYBOARD` | No declared keyboard lists the field and it is no system text field; or `SELECT` did not open the keyboard; or `app.keyboard` finds none open. | | `AMBIGUOUS_KEYBOARD` | Several declared keyboards are on screen and none holds focus. | | `CHAR_NOT_ON_KEYBOARD` | No key types the character on any layer reached. | | `TEXT_NOT_ENTERED` | After typing, the field does not show the text (a key typed something else, or the app rejected it). | | `KEYBOARD_ACTION_MISSING` | `erase`, `submit` or clearing need a key the keyboard does not declare or show. | | `NOT_EDITABLE` | `toHaveValue` on an element that is not a system text field. | | `SECURE_FIELD` | `toHaveValue` on a secure field. | | `DUPLICATE_KEYBOARD` | Two keyboards share a name. | All codes: [errors](/reference/core/docs/errors). --- # Text snapshots Source: https://yusufyildirim.github.io/toets/reference/core/docs/text-snapshots.md A text snapshot is a small YAML outline of what the user sees: visible, on-screen elements, their text and their state. It is the cheapest way to assert a whole screen, and the format AI agents read best. ```ts nocheck await expect(app.getByTestId('rail')).toMatchTextSnapshot(` - rail: - card_1 "Movie 1" [focused] - card_2 "Movie 2" `); await expect(app).toMatchTextSnapshot(); // per-platform baseline file ``` ## Format - One entry per element: `- name "text" [states]`. The name is the test ID, else `text`, else `element`. - States: `focused`, `selected`, `busy`, `disabled`, `offscreen`, then `editable` and `secure` for system text fields, whose entry ends with their value instead of text: `- email [editable] value="ada@example.com"`, `- password [editable, secure] value="••••"`. - A declared app keyboard is one line without children: `- 'osk [keyboard: search, layer: lower, focused: "m"]'` (quoted: YAML). A snapshot of the keyboard's root lists its keys. See [text input](/reference/core/docs/text-input). - Only visible elements inside the viewport are listed, plus the focused element even when it is offscreen. Wrappers with no test ID, text or state are flattened away. - An empty screen is `[]`. ## Principles - **Inline for intent, files for coverage.** An inline snapshot documents what matters in the test. Without an argument the snapshot is compared to a baseline file per project (platform), updated with `--update-snapshots`. A missing baseline is written and the test fails once (Playwright's `toMatchSnapshot`); file names carry the host OS (`-darwin`, `-linux`) unless `snapshotPathTemplate` drops `{platform}`. - **Indentation is ignored** in inline snapshots, so they can follow the code's indentation. - **Retried like any assertion** until it matches or times out; the failure shows a line diff. - **`app.snapshot()`** returns the same text, handy for debugging and for agents. ## TV trap: offscreen rail items Rails keep offscreen items in the tree. They are left out of snapshots on purpose, so a snapshot does not change when an item scrolls in from far away, only when the user can see it. ## Parity trap: nesting comes from the tree The outline nests like the tree it is read from. The SDK tree and the web DOM nest like the app's components, but a black-box platform tree may not: React Native on Android lists a plain `View`'s descendants as its siblings (see the Android TV driver's traps). An inline snapshot meant for every platform should cover a container that keeps its children everywhere, or run with `toets.sdk`. --- # Error codes Source: https://yusufyildirim.github.io/toets/reference/core/docs/errors.md Every toets error has a stable `code`. In test output it reads `ToetsError: [CODE] message`, followed by `Hint:` (likely cause and fix) and `Docs:` (the page to read). Act on the hint first; branch on the code, never on the message. A `Docs:` path of the form `reference//docs/` ships with that package at `node_modules/@toets//docs/.md`; other paths (`concepts/focus`) are pages of the docs site. Codes from the SDK host (`sdk.*`) surface as `ToetsError` with the same code. ## @toets/core | Code | Meaning | Docs | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `AMBIGUOUS_KEYBOARD` | `app.keyboard` found several declared keyboards on screen and none holds focus. | [text-input](/reference/core/docs/text-input) | | `APP_NOT_LAUNCHED` | `app.openDeepLink` before `app.launch`: there is no running app to deliver the link to. | [deep-links](/reference/core/docs/deep-links) | | `CAPABILITY_MISSING` | The action or assertion needs a capability this target does not have (driver, SDK domain or mock server). | [capabilities](/reference/core/docs/capabilities) | | `CHAR_NOT_ON_KEYBOARD` | An app keyboard has no key for a character on any layer its declared toggles reach. | [text-input](/reference/core/docs/text-input) | | `DEEPLINK_INVALID` | A deep link is not an absolute URL, or the platform's `deepLink` mapper threw or returned something the platform can not open. Also in @toets/driver-android-tv, @toets/driver-tvos, @toets/driver-web. | [deep-links](/reference/core/docs/deep-links) | | `DEVICE_COMMAND_FAILED` | A `command` device provider command failed. | [test/devices](/reference/test/docs/devices) | | `DEVICE_COMMAND_OUTPUT` | The device acquire command must print JSON with an "address" on its last line; got. | [test/devices](/reference/test/docs/devices) | | `DRIVER_CONTRACT` | A driver returned something that breaks the `Driver` contract (a driver bug). | [drivers](/reference/core/docs/drivers), [capabilities](/reference/core/docs/capabilities) | | `DUPLICATE_KEYBOARD` | Two keyboards in the `keyboards` option share a name. | [text-input](/reference/core/docs/text-input) | | `ELEMENT_DETACHED` | The element a locator resolved to left the screen before it could be read. | [text-snapshots](/reference/core/docs/text-snapshots) | | `ELEMENT_NOT_FOUND` | A locator matched no element within the timeout. | [focus-navigation](/reference/core/docs/focus-navigation), [text-input](/reference/core/docs/text-input), [locators](/reference/core/docs/locators) | | `ELEMENT_OFFSCREEN` | Cannot screenshot an element outside the viewport. | [screenshots](/reference/core/docs/screenshots) | | `FOCUS_LOOP` | `pressUntilFocused`: focus came back to an element it already left (a wrap-around). | [focus-navigation](/reference/core/docs/focus-navigation) | | `FOCUS_STUCK` | `pressUntilFocused`: a press did not move focus within `navigationSettleMs`. | [focus-navigation](/reference/core/docs/focus-navigation) | | `FOCUS_UNCHANGED` | Focus stayed on … for …ms after the action. | [focus-navigation](/reference/core/docs/focus-navigation) | | `FOCUS_UNREACHABLE` | `pressUntilFocused` or `navigateTo` gave up: `maxPresses` presses, or no direction left to try. | [focus-navigation](/reference/core/docs/focus-navigation) | | `INVALID_ARGUMENT` | An API received an invalid argument, such as a value that is not a toets Locator or a negative count. | [screenshots](/reference/core/docs/screenshots), [focus-navigation](/reference/core/docs/focus-navigation), [text-input](/reference/core/docs/text-input), [locators](/reference/core/docs/locators), [assertions](/reference/core/docs/assertions), [remote](/reference/core/docs/remote) | | `INVALID_DRIVER` | The configured driver module does not default-export a matching `DriverModule`. | [test/config](/reference/test/docs/config) | | `INVALID_SCREENSHOT` | Not a toets screenshot. | [screenshots](/reference/core/docs/screenshots) | | `INVALID_SUBJECT` | A matcher received a subject it does not support. Also in @toets/test. | [assertions](/reference/core/docs/assertions) | | `KEY_UNSUPPORTED` | The platform's remote has no such key, or cannot hold keys. | [remote](/reference/core/docs/remote) | | `KEYBOARD_ACTION_MISSING` | A text action needs a key (`backspace`, `clear`, `submit`) the keyboard does not declare or show. | [text-input](/reference/core/docs/text-input) | | `MOCK_DISABLED` | Network mocking is not enabled for this project. | [network](/reference/core/docs/network) | | `MOCK_UNAVAILABLE` | Network mocking is on, but no mock server is set. | [network](/reference/core/docs/network) | | `MODULE_NOT_FOUND` | Cannot find … (…). | [test/config](/reference/test/docs/config) | | `NO_DEVICES` | No device addresses were configured for `external` devices. | [test/devices](/reference/test/docs/devices) | | `NO_FOCUS` | Nothing holds focus, before moving focus or after a press. | [focus-navigation](/reference/core/docs/focus-navigation) | | `NO_KEYBOARD` | No keyboard for the field: it is no system text field and no declared keyboard lists it, or the declared keyboard did not open. | [text-input](/reference/core/docs/text-input) | | `NO_MANAGED_DEVICES` | The driver cannot manage devices for this platform. | [test/devices](/reference/test/docs/devices) | | `NOT_EDITABLE` | `toHaveValue` on an element that is not a system text field. | [text-input](/reference/core/docs/text-input) | | `NOT_ENOUGH_DEVICES` | There are fewer `external` devices than workers. | [test/devices](/reference/test/docs/devices) | | `SDK_NOT_CONNECTED` | The app did not connect to the toets SDK host at … within …ms. | [sdk](/reference/core/docs/sdk) | | `SECURE_FIELD` | `toHaveValue` on a secure (password) field, whose value is masked. | [text-input](/reference/core/docs/text-input) | | `STRICT_MODE_VIOLATION` | A locator matched several elements where exactly one is needed. | [locators](/reference/core/docs/locators) | | `TEXT_NOT_ENTERED` | After typing, the field does not show exactly the text. | [text-input](/reference/core/docs/text-input) | | `UNKNOWN_KEY` | Unknown key …. | [remote](/reference/core/docs/remote) | ## @toets/test | Code | Meaning | Docs | | ---------------------- | ------------------------------------------ | ---------------------------------------- | | `NEGATION_UNSUPPORTED` | The matcher cannot be negated with `.not`. | [assertions](/reference/core/docs/assertions) | | `NOT_A_TOETS_PROJECT` | Project "…" is not a toets project. | [test/config](/reference/test/docs/config) | ## @toets/driver-web | Code | Meaning | Docs | | ----------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `WEB_ELEMENT_OFFSCREEN` | The element is outside the viewport. | | | `WEB_EVALUATE_FAILED` | Reading the page failed. | | | `WEB_INVALID_CONFIG` | The web app config or `webDriver()` options are malformed (`url`, `keys`, ...). | [driver-web/keys](/reference/driver-web/docs/keys), [driver-web/options](/reference/driver-web/docs/options) | | `WEB_KEY_UNMAPPED` | Key … has no web key mapping. | [driver-web/keys](/reference/driver-web/docs/keys) | | `WEB_LAUNCH_FAILED` | Could not load the app at …. | [driver-web/setup](/reference/driver-web/docs/setup) | | `WEB_NO_DOCUMENT` | The page has no document element to read. | | | `WEB_NO_TEXT_FIELD` | System text entry on web found no text field holding focus in the page. | [text-input](/reference/core/docs/text-input) | | `WEB_NOT_CHROMIUM` | The web driver needs a Chromium page. | [driver-web/setup](/reference/driver-web/docs/setup) | | `WEB_NOT_RECORDING` | No recording is running. | | | `WEB_NOT_STARTED` | The web driver is not started. | | | `WEB_PAGE_CLOSED` | The page passed to the web driver is closed. | [driver-web/setup](/reference/driver-web/docs/setup) | | `WEB_RECORDING_ACTIVE` | A recording is already running. | | | `WEB_STALE_ELEMENT` | The element is no longer in the document. | | | `WEB_START_FAILED` | Could not open a browser page. | [driver-web/setup](/reference/driver-web/docs/setup) | ## @toets/driver-android-tv | Code | Meaning | Docs | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `ANDROID_APP_CONFIG` | … has no launcher activity (LEANBACK_LAUNCHER or LAUNCHER). | [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_APP_NOT_INSTALLED` | … is not installed on …. | [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_APPIUM_START_FAILED` | Appium did not start on port …. | [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_AVD_FAILED` | Creating AVD … failed. | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices) | | `ANDROID_COMMAND_FAILED` | `…` failed (exit …). | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices), [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_COMMAND_TIMEOUT` | `…` did not finish within …ms. | | | `ANDROID_DEVICE_NOT_READY` | … did not finish booting within …ms. | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices) | | `ANDROID_ELEMENT_DETACHED` | The element is no longer on screen. | [driver-android-tv/traps](/reference/driver-android-tv/docs/traps) | | `ANDROID_EMULATOR_FAILED` | No free emulator port from … to …. | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices) | | `ANDROID_KEY_UNSUPPORTED` | Key … is not available on the '…' remote. | [driver-android-tv/keys](/reference/driver-android-tv/docs/keys) | | `ANDROID_LAUNCH_FAILED` | Launching … failed. | [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_NO_DEVICE` | No Android device to run on. | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices) | | `ANDROID_NO_TEXT_FIELD` | System text entry found no focused field (`fill`, `app.keyboard` on a system field). | [driver-android-tv/capabilities](/reference/driver-android-tv/docs/capabilities) | | `ANDROID_NOT_A_TV` | … is not an Android TV device. | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices) | | `ANDROID_NOT_STARTED` | The Android TV driver is not started. | | | `ANDROID_RECORDING_FAILED` | stopRecording() called without a recording. | | | `ANDROID_SDK_NOT_FOUND` | Android SDK not found. | [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_SESSION_FAILED` | Could not open a UiAutomator2 session on …. | [driver-android-tv/setup](/reference/driver-android-tv/docs/setup) | | `ANDROID_SYSTEM_IMAGE_MISSING` | No … system image for API … (…) is installed. | [driver-android-tv/devices](/reference/driver-android-tv/docs/devices) | | `DEEPLINK_UNHANDLED` | No activity, registered URL scheme or served page of the app handles the translated deep link. Also in @toets/driver-tvos, @toets/driver-web. | [deep-links](/reference/core/docs/deep-links) | ## @toets/driver-tvos | Code | Meaning | Docs | | --------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `TVOS_APP_NOT_INSTALLED` | … is not installed on simulator …. | [driver-tvos/setup](/reference/driver-tvos/docs/setup) | | `TVOS_APPIUM_START_FAILED` | Appium did not start on …. | [driver-tvos/setup](/reference/driver-tvos/docs/setup) | | `TVOS_BOOT_FAILED` | Simulator … did not boot. | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_COMMAND_FAILED` | Opening … failed. | [driver-tvos/traps](/reference/driver-tvos/docs/traps), [driver-tvos/capabilities](/reference/driver-tvos/docs/capabilities) | | `TVOS_CONFIG` | managed.namePrefix "…" does not start with "toets". | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators), [driver-tvos/setup](/reference/driver-tvos/docs/setup) | | `TVOS_DEVICE_TYPE_MISSING` | The requested Apple TV device type is not available for the tvOS runtime. | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_ELEMENT_DETACHED` | Element … is no longer on screen. | [driver-tvos/traps](/reference/driver-tvos/docs/traps) | | `TVOS_ELEMENT_NOT_VISIBLE` | Element … is not visible on screen. | [driver-tvos/traps](/reference/driver-tvos/docs/traps) | | `TVOS_KEY_UNSUPPORTED` | The Siri Remote has no button for …. | [driver-tvos/remote](/reference/driver-tvos/docs/remote) | | `TVOS_NO_DEVICE` | No tvOS simulator to drive. | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_NO_TEXT_FIELD` | System text entry on tvOS found no focused text field. | [driver-tvos/capabilities](/reference/driver-tvos/docs/capabilities) | | `TVOS_NOT_A_TVOS_SIMULATOR` | Simulator … (…) runs …, not tvOS. | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_NOT_STARTED` | The tvOS driver is not started. | | | `TVOS_RECORDING_FAILED` | A recording is already running. | [driver-tvos/capabilities](/reference/driver-tvos/docs/capabilities) | | `TVOS_RUNTIME_MISSING` | No installed tvOS simulator runtime. | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_SESSION_FAILED` | Could not open an Appium XCUITest session on …. | [driver-tvos/setup](/reference/driver-tvos/docs/setup) | | `TVOS_SIMCTL_FAILED` | `xcrun …` failed (exit …). | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_SIMULATOR_NOT_FOUND` | No simulator with UDID … in …. | [driver-tvos/simulators](/reference/driver-tvos/docs/simulators) | | `TVOS_WDA_BUILD_FAILED` | Building WebDriverAgent for tvOS Simulator failed (exit …). | [driver-tvos/setup](/reference/driver-tvos/docs/setup) | ## @toets/mock | Code | Meaning | Docs | | --------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `MOCK_BAD_ORIGIN` | The origin header is not an `http(s)` origin. | [mock/app-integration](/reference/mock/docs/app-integration) | | `MOCK_BAD_REQUEST` | The request could not be turned into a Fetch `Request` (e.g. unsupported method). | [mock/concepts](/reference/mock/docs/concepts) | | `MOCK_CLIENT_ABORTED` | The app closed the connection before the response completed. | | | `MOCK_HANDLER_ERROR` | A handler threw. | [mock/writing-handlers](/reference/mock/docs/writing-handlers) | | `MOCK_INTERNAL_ERROR` | An unexpected failure inside the mock server (a toets bug: please report it). | [mock/concepts](/reference/mock/docs/concepts) | | `MOCK_INVALID_HANDLER` | `use()` / `resetHandlers()` received something that is not an MSW request handler. | [mock/writing-handlers](/reference/mock/docs/writing-handlers) | | `MOCK_INVALID_OPTION` | An option passed to `createMockServer()`, `latency()` or `failure()` is invalid. | [mock/writing-handlers](/reference/mock/docs/writing-handlers) | | `MOCK_LISTEN_FAILED` | The server could not start listening for another reason. | [mock/concepts](/reference/mock/docs/concepts) | | `MOCK_NETWORK_ERROR` | A handler returned `HttpResponse.error()`: the connection is dropped on purpose. | | | `MOCK_NO_ORIGIN` | No handler matched and the request has no origin header, so there is nowhere to proxy. | [mock/app-integration](/reference/mock/docs/app-integration) | | `MOCK_PORT_IN_USE` | The requested port is taken. | [mock/concepts](/reference/mock/docs/concepts) | | `MOCK_RESPONSE_FAILED` | The response body failed after headers were sent (upstream reset, broken mock stream). | | | `MOCK_UNHANDLED` | No handler matched and the server runs with `onUnhandledRequest: 'reject'`. | [mock/writing-handlers](/reference/mock/docs/writing-handlers) | | `MOCK_UPSTREAM_UNREACHABLE` | Proxying to the real upstream failed before a response arrived. | [mock/concepts](/reference/mock/docs/concepts) | ## @toets/protocol | Code | Meaning | Docs | | ------------------------ | ---------------------------------------------------------------------------------- | -------------------------------------------- | | `sdk.closed` | The session closed (app quit, crashed or reloaded) before the request completed. | [protocol/host](/reference/protocol/docs/host) | | `sdk.host-closed` | The host was closed while waiting or requesting. | [protocol/host](/reference/protocol/docs/host) | | `sdk.listen-failed` | The host could not open its WebSocket server. | [protocol/host](/reference/protocol/docs/host) | | `sdk.method-unsupported` | The SDK did not announce the domain, or its protocol version predates the method. | [protocol/spec](/reference/protocol/docs/spec) | | `sdk.remote-error` | The SDK answered with an error. `rpcCode` and `data` carry the details. | | | `sdk.request-timeout` | The app did not answer a request in time. | [protocol/host](/reference/protocol/docs/host) | | `sdk.session-timeout` | The app did not complete the handshake in time. | [protocol/host](/reference/protocol/docs/host) | | `sdk.unknown-token` | `waitForSession` was called with a token this host never issued (or that expired). | [protocol/host](/reference/protocol/docs/host) | ## @toets/mcp | Code | Meaning | Docs | | ---------------------- | ------------------------------------------------ | ------------------------------------ | | `MCP_BAD_INPUT` | A target needs `testId` and/or `text`. | [mcp/tools](/reference/mcp/docs/tools) | | `MCP_CONFIG_INVALID` | Invalid toets MCP …. | [mcp/setup](/reference/mcp/docs/setup) | | `MCP_CONFIG_NOT_FOUND` | Config not found at …. | [mcp/setup](/reference/mcp/docs/setup) | | `MCP_NO_CONFIG` | No toets config, so there is no target to drive. | [mcp/setup](/reference/mcp/docs/setup) | | `MCP_NOT_LAUNCHED` | The app is not running yet. | [mcp/tools](/reference/mcp/docs/tools) | | `MCP_UNKNOWN_TARGET` | Unknown target "…". | [mcp/setup](/reference/mcp/docs/setup) | --- # App integration Source: https://yusufyildirim.github.io/toets/reference/mock/docs/app-integration.md The mock server only sees requests the app sends to it. In test runs the launch payload carries `mockUrl` (e.g. `http://localhost:53124`); the app sends each API request to `mockUrl + path` with the real origin in the `x-toets-original-origin` header. Without `mockUrl` (production, manual runs) nothing changes. Rules: - Keep the path and query; only the origin moves to the header. `https://api.tv.example/v2/rails?page=2` becomes `GET {mockUrl}/v2/rails?page=2` with `x-toets-original-origin: https://api.tv.example`. - The header holds an origin only (scheme, host, port), never a path. - Route every API client (and absolute URLs found in responses, like pagination links) through the same function. - Read `mockUrl` once at startup from the launch payload. The toets SDK exposes it as `getLaunchPayload()?.mockUrl`, with or without the SDK session; without the SDK, read the `__toets` launch parameter yourself (web: `?__toets=` query parameter, Android: intent string extra, tvOS: launch argument) and parse `mockUrl` from the JSON. ## fetch ```ts declare function getMockUrl(): string | undefined; // from the launch payload const MOCK_HEADER = 'x-toets-original-origin'; /** Rewrites a real API URL to the mock server when the launch payload has a mockUrl. */ export function routeRequest(url: string, mockUrl: string | undefined) { if (!mockUrl) return { url, headers: {} }; const real = new URL(url); return { url: mockUrl + real.pathname + real.search, headers: { [MOCK_HEADER]: real.origin }, }; } export function apiFetch(url: string, init: RequestInit = {}): Promise { const routed = routeRequest(url, getMockUrl()); // getMockUrl(): from the launch payload const headers = new Headers(init.headers); for (const [name, value] of Object.entries(routed.headers)) headers.set(name, value); return fetch(routed.url, { ...init, headers }); } ``` ## axios ```ts nocheck import axios from 'axios'; export const api = axios.create({ baseURL: 'https://api.tv.example/v2' }); api.interceptors.request.use((config) => { const mockUrl = getMockUrl(); if (!mockUrl) return config; const real = new URL(api.getUri(config)); // full URL incl. baseURL and params config.baseURL = mockUrl; config.url = real.pathname + real.search; config.params = undefined; // already serialized into real.search config.headers.set('x-toets-original-origin', real.origin); return config; }); ``` ## Platform setup - **Android**: cleartext HTTP is blocked by default since Android 9. Allow it for `localhost` in debug builds with a network security config (`localhost` with `cleartextTrafficPermitted="true"`). toets runs `adb reverse` for the mock port, so `localhost` on the device reaches the host. - **tvOS**: App Transport Security blocks plain HTTP. Set `NSAppTransportSecurity > NSAllowsLocalNetworking = YES` in debug builds. The simulator shares the host network. - **Web**: nothing to configure. The server answers CORS and Private Network Access preflights; browsers allow `http://localhost` from `https` pages. ## Checking it works Launch, trigger one API call, then look at `app.network.requests()`. An empty list means the app is not routing; a record with `error.code === 'MOCK_NO_ORIGIN'` means the header is missing. --- # Asserting requests Source: https://yusufyildirim.github.io/toets/reference/mock/docs/asserting-requests.md Every request that reaches the mock server is recorded, mocked or proxied. Assert on behavior the user can not see: the right call was made, with the right body, once. ```ts run import { test, expect, Key } from '@toets/test'; test('liking a video posts to the API once', async ({ app }) => { await app.launch(); await app.focus.navigateTo(app.getByTestId('like-button')); await app.remote.press(Key.SELECT); await expect(app.network).toHaveRequested({ method: 'POST', url: '/v1/likes' }); const [like] = await app.network.requests({ method: 'POST', url: '/v1/likes' }); expect(JSON.parse(like!.body!)).toEqual({ videoId: 'v1' }); }); ``` Prefer the retrying matcher over reading `requests()` right after an action: the request may still be in flight. ## Filters `requests({ method, url })`: - `method` is case-insensitive. - A string `url` uses the same rules as handler paths: relative paths match any origin, `:params` and `*` work, the query string is ignored. - A RegExp is tested against the full URL **including** the query string: `{ url: /\/search\?q=news/ }`. ## What a record holds | Field | Notes | | ---------------------- | --------------------------------------------------------------------------- | | `url` | The URL the app meant: original origin + path + query | | `headers` | As the app sent them, lowercase names | | `body`, `bodyEncoding` | UTF-8 text, or base64 for binary bodies | | `mocked` | `true` when a handler answered, `false` when proxied or failed | | `status` | `null` while in flight or when the connection was dropped | | `error` | `{ code, message }` when the request failed (see [concepts](/reference/mock/docs/concepts)) | | `response` | Status, headers and decoded body the app received | | `id` | Same value as the `x-toets-request-id` response header | Bodies above `maxRecordedBodyBytes` (1 MiB) are recorded truncated (`bodyTruncated`) and always forwarded in full. ## HAR `MockServer.toHar(filter?)` exports the recorded traffic as HAR 1.2 (open it in browser devtools or any HAR viewer). toets attaches each test's HAR to its report; failed exchanges have `status: 0` or the error status plus `_toets.error`. ## TV trap A negative assertion ("never called `/v1/ads`") only proves the app did not call it **through the mock server**. Make sure every client in the app routes through `mockUrl` before relying on absence. --- # Network mocking: concepts Source: https://yusufyildirim.github.io/toets/reference/mock/docs/concepts.md toets mocks HTTP on the **test host**, not inside the app. A small HTTP server (the mock server) runs next to the test runner; the app sends its API traffic there. Handlers are [MSW](https://mswjs.io) request handlers, so they run in Node with your test code and can close over test state. ``` app GET {mockUrl}/v1/rails x-toets-original-origin: https://api.tv.example mock handler matches? yes -> mocked response no -> proxy GET https://api.tv.example/v1/rails, stream the response back ``` This is a **cooperative proxy**: the app opts in by routing requests to `mockUrl` (from the launch payload) and naming the real origin in the `x-toets-original-origin` header. No MITM certificates, no system proxy, identical on web, Android TV and tvOS. See [app integration](/reference/mock/docs/app-integration). ## Request flow 1. CORS preflights are answered directly (permissive, incl. Private Network Access) and not recorded. 2. The request is rebuilt as the app meant it: origin header + path, e.g. `https://api.tv.example/v1/rails`. Handlers and the upstream see exactly what the real API would see (the toets header and hop-by-hop headers removed, `host` set). 3. Handlers run in order; the first one returning a response wins. 4. No response: the request is proxied to the original origin and the response streamed back unchanged (status, headers, compressed bytes). Same-origin redirects are rewritten so they stay on the mock server. 5. Every exchange is recorded: request, response, timing, whether it was mocked, and why it failed. ## Isolation model - **One mock server per worker**, started once, its URL passed to every launch. Ports are picked by the OS, so workers never collide. - **Handlers reset per test.** Baseline handlers (`createMockServer({ handlers })`, or `toets: { mock: { handlers } }` in a toets config) always apply; handlers added in a test with `app.network.use()` are removed after it. Recordings are cleared per test too. - **Hermetic runs**: with `onUnhandledRequest: 'reject'` (in `createMockServer` or `toets.mock`) unmatched requests fail with `MOCK_UNHANDLED` instead of reaching the real API. - **Concurrency is safe.** Requests are handled in parallel; each one resolves against the handler list as it was when it arrived, so a reset never affects a request in flight. ## Failures are explicit When the mock server can not do what the app asked, it answers with a JSON body `{ "toetsError": { code, message, hint, docs } }`, an `x-toets-error` header, and records the error on the request: | Code | Status | Meaning | | --------------------------- | ------ | ------------------------------------------------------------- | | `MOCK_NO_ORIGIN` | 502 | No handler matched and no origin header: nowhere to proxy | | `MOCK_UNHANDLED` | 502 | No handler matched and the server rejects unhandled requests | | `MOCK_UPSTREAM_UNREACHABLE` | 502 | Proxying failed (DNS, refused, TLS, ...) | | `MOCK_BAD_ORIGIN` | 400 | The origin header is not an `http(s)` origin | | `MOCK_HANDLER_ERROR` | 500 | A handler threw | | `MOCK_NETWORK_ERROR` | none | A handler returned `HttpResponse.error()`; connection dropped | | `MOCK_RESPONSE_FAILED` | none | The body broke after headers were sent | Every response also carries `x-toets-request-id`, matching the recorded request's `id`, to correlate app logs with recordings. ## Not covered - WebSockets and other protocol upgrades (answered `501`). - Traffic the app does not route: native players, image loaders, third-party SDKs. See [TV traps](/reference/mock/docs/tv-traps). --- # Network mocking: TV traps Source: https://yusufyildirim.github.io/toets/reference/mock/docs/tv-traps.md Where web intuition about request mocking is wrong on TV. ## Media is not API traffic Video manifests and segments (HLS, DASH) are fetched by native players (ExoPlayer/Media3, AVPlayer) or by MSE inside the player library, not by your API client. Do not route them through the mock server: it adds latency to every segment and records megabytes. Mock the **API response that names the stream** instead, pointing it at a small, stable test stream on a real CDN or a local static server. ## Images bypass your client Image components load URLs with their own stack and can not add the origin header. Image URLs inside mocked JSON should point at real hosts or a local static server. If an app does rewrite image URLs to `mockUrl`, those requests arrive without the header: they fail with `MOCK_NO_ORIGIN` unless a handler matches them (e.g. `http.get('/images/*', ...)` returning bytes). ## Third-party SDKs are invisible Analytics, ads, DRM licence servers, crash reporters and player telemetry use their own HTTP clients. They neither route through the mock server nor show up in `requests()`. Stub them at the app's configuration level for tests, or accept that they hit the network. ## Absolute URLs in responses Pagination links, deep links and redirects often carry absolute URLs to the real host. If the app follows them with a client that does not route, those calls skip the mock. Same-origin redirects are rewritten by the mock server; cross-origin ones are not. ## Cookies are scoped to the real domain `Set-Cookie: ...; Domain=api.tv.example` is rejected by a web app talking to `localhost`. Token-based auth works unchanged; cookie auth may need a handler that issues host-only cookies in tests. ## Cleartext and transport security Android blocks cleartext HTTP and tvOS enforces ATS by default, so the first symptom of a missing debug config is "all requests fail" with no record at all. See [app integration](/reference/mock/docs/app-integration#platform-setup). ## Timeouts are real `latency()` above the app's own request timeout produces the app's timeout behavior, not a slow success. TV apps often use long timeouts (30s+); test timeouts with `latency('infinite')` plus a shortened app timeout via launch flags rather than waiting. --- # Writing handlers Source: https://yusufyildirim.github.io/toets/reference/mock/docs/writing-handlers.md Handlers are standard [MSW `http` handlers](https://mswjs.io/docs/api/http). In tests, import the helpers on this page from `@toets/test`, which re-exports them from `@toets/mock` so the server and your handlers share one MSW copy. ```ts run import { test, expect, http, HttpResponse } from '@toets/test'; test('shows an empty state when there are no rails', async ({ app }) => { app.network.use(http.get('/v1/rails', () => HttpResponse.json([]))); await app.launch(); await expect(app.getByTestId('rails-empty')).toBeVisible(); }); ``` ## Matching - **Relative paths match any origin**: `'/v1/rails'` matches `https://api.tv.example/v1/rails` and the same path on any other host. Most apps talk to one API, so this is the default to reach for. - **Absolute URLs pin a host**: `'https://api.tv.example/v1/rails'`. Use them when several APIs share paths. - Params and wildcards follow MSW: `'/v1/items/:id'`, `'*/items'`, RegExp. Query strings never take part in matching; read them from `new URL(request.url).searchParams`. ## Order and lifetime `use()` prepends. Within one call the first handler wins; across calls the latest call wins. Handlers added in a test are removed after it; baseline handlers from config stay. A resolver that returns nothing falls through to the next handler, then to the upstream. ## Pass-through and real responses - `passthrough()` sends a matched request to the real API unchanged. - `fetch(bypass(request))` inside a resolver fetches the real response so you can patch it. ## Latency and failures Two helpers build handlers for the unhappy path. They work on mocked and proxied traffic alike. ```ts nocheck import { failure, latency } from '@toets/test'; app.network.use(latency(3000, { url: '/v1/rails' })); // slow, then normal response app.network.use(failure({ url: '/v1/rails', status: 503, times: 1 })); // fails once, then recovers app.network.use(failure({ url: '/v1/me' })); // connection dropped (network error) ``` `latency()` only delays requests that reach it: put it before the handlers it should slow down (first in the same `use()` call, or in a later call). `latency('infinite')` never answers, for testing timeouts. Inside your own resolvers use MSW's `delay(ms)`. ## TV trap Handlers only see traffic the app routes to the mock server. If a mock "does nothing", check `app.network.requests()` first: an absent request means the app called the real host directly. See [app integration](/reference/mock/docs/app-integration) and [TV traps](/reference/mock/docs/tv-traps). --- # Web capabilities Source: https://yusufyildirim.github.io/toets/reference/driver-web/docs/capabilities.md The driver declares only what a browser really delivers. Tests `requires` the rest and are skipped with a reason instead of failing. | Capability | Web driver | | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key.back`, `key.info`, `key.media.*`, `key.color`, `key.numeric`, `key.channel` | yes, while mapped in [`keys`](/reference/driver-web/docs/keys) | | `key.home`, `key.menu` | only if you map them | | `key.longpress` | yes (keydown, repeats, keyup) | | `text.input` | yes: the focused ``, `