# spana — Web-first, TypeScript-native E2E testing (Web, iOS, Android, Electron, Electrobun) > Docs: https://spana.antonwester.se/ > Full documentation for AI/LLM consumption. > For links-only version, see https://spana.antonwester.se/llms.txt > > Generated from source docs — do not edit manually. --- ## Introduction spana is a TypeScript-native end-to-end testing framework for React Native and web applications. It lets you write a single test file that runs against a browser, an Android device or emulator, and an iOS simulator or device — without modifying the app under test. ## Why spana Existing E2E tools fall into two camps: - **YAML-based runners** (Maestro, Detox scripts) — readable but limited. No real TypeScript, no imports, no abstractions. - **Platform-native tools** (Espresso, XCUITest) — powerful but siloed. You write Android tests in Kotlin and iOS tests in Swift. spana occupies the gap: full TypeScript with real imports, types, and async/await, running across all three platforms from one file. It replaces Maestro's JVM/YAML stack with a pure-TypeScript engine. No companion JVM process. No YAML parsing. No patching the app binary. ## Key principles **Pure TypeScript.** Tests are `.ts` files. You get autocomplete, type errors, imports, and the full JS ecosystem. The test runner works with both Node.js 20+ and Bun. **No app modification.** spana never requires adding a test server, special build flag, or SDK to your app. Interaction happens through the platform's accessibility layer (UiAutomator2, WebDriverAgent, Playwright CDP). **Agent-first.** The CLI exposes `hierarchy`, `selectors`, and `validate` commands designed for AI agent workflows. `--reporter json` produces structured output suitable for piping to an agent. **Thin drivers.** Raw platform drivers are HTTP clients with no logic. All selector matching, auto-wait, and retry runs in the TypeScript smart layer on the host machine. ## Platform support | Platform | Driver | Notes | | ------------- | -------------------------- | ----------------------------------------------------------------- | | Web / RN Web | Playwright (CDP) | No companion binary — Playwright is a dev dependency | | Android | UiAutomator2 HTTP client | Bundled APK server (~2–3 MB), ADB-forwarded | | iOS Simulator | WebDriverAgent HTTP client | Bundled unsigned XCTest bundle (~5 MB) | | iOS Device | WebDriverAgent HTTP client | Re-signed with user certificate via `codesign`; requires `iproxy` | ## Monorepo structure The `spana` package (`packages/spana`) is the core library and CLI. Source is organized into: - `src/api/` — `flow()`, `app`, `expect` — the public test-writing API - `src/core/` — engine, orchestrator, parallel runner - `src/smart/` — coordinator, auto-wait, element-matcher (all TypeScript, no native code) - `src/drivers/` — thin HTTP clients for each platform - `src/agent/` — `session.ts` backing `spana hierarchy` and `spana selectors` - `src/cli/` — CLI entry point - `src/schemas/` — shared types: `Element`, `Selector`, `Platform`, `SpanaConfig` --- ## Quick Start ## 1. Install ```bash npm install spana-test # or bun add spana-test ``` spana works with Node.js 20+ and [Bun](https://bun.sh). ## 2. Create a config file Create `spana.config.ts` at the root of your project: ```ts import { defineConfig } from "spana-test"; export default defineConfig({ apps: { web: { url: "http://localhost:3000" }, android: { packageName: "com.example.app" }, ios: { bundleId: "com.example.app" }, }, platforms: ["web"], }); ``` Start with `platforms: ["web"]` while getting familiar with the framework, then add `"android"` and `"ios"` once your device targets are set up. ## 3. Write a flow Create `flows/login.ts`: ```ts import { flow } from "spana-test"; export default flow("user can log in", async ({ app, expect }) => { await app.tap({ testID: "email-input" }); await app.inputText("user@example.com"); await app.tap({ testID: "password-input" }); await app.inputText("secret"); await app.tap({ testID: "login-button" }); await expect({ testID: "home-screen" }).toBeVisible(); }); ``` The `testID` selector maps to `data-testid` on web, `accessibilityIdentifier` on iOS, and `resource-id` on Android. It is the preferred selector type. ## 4. Run ```bash spana test ``` This discovers all `*.ts` files under `./flows` (or the `flowDir` in your config) and runs them against the configured platforms. ### Run a single file ```bash spana test flows/login.ts ``` ### Target a specific platform ```bash spana test --platform android ``` ### Filter by tag ```bash spana test --tag smoke ``` ## 5. View results By default, results print to the console. To get structured JSON output: ```bash spana test --reporter json ``` On failure, spana captures screenshots and diagnostics under `spana-output/` by default (configurable via `artifacts.outputDir`). ## Next steps - [Configuration](/getting-started/configuration/) — all `defineConfig` options - [Flows](/writing-tests/flows/) — `flow()` API, tags, timeouts - [Selectors](/writing-tests/selectors/) — all selector types - [CLI Commands](/cli/commands/) — all flags --- ## Configuration Configuration lives in `spana.config.ts` at the project root. Pass the config object to `defineConfig` for type safety. ```ts import { defineConfig } from "spana-test"; export default defineConfig({ // ... }); ``` Use `--config ./path/to/spana.config.ts` to specify a different location. Run `spana validate-config` to validate the file without starting drivers or discovering flows. ## Full example ```ts import { defineConfig } from "spana-test"; export default defineConfig({ apps: { web: { url: "http://localhost:3000" }, android: { packageName: "com.example.app", appPath: "./builds/app.apk" }, ios: { bundleId: "com.example.app", appPath: "./builds/App.app", signing: { teamId: "ABCDE12345" }, }, }, platforms: ["web", "android", "ios"], parallelPlatforms: true, flowDir: "./flows", reporters: ["console", "json", "html"], defaults: { waitTimeout: 5000, pollInterval: 200, settleTimeout: 250, initialPollInterval: 50, waitForIdleTimeout: 150, typingDelay: 20, retries: 2, retryDelay: 250, workers: 2, }, artifacts: { outputDir: "./spana-output", captureOnFailure: true, captureOnSuccess: false, captureSteps: false, screenshot: true, uiHierarchy: true, consoleLogs: true, jsErrors: true, har: true, }, execution: { web: { browser: "chromium", headless: true, verboseLogging: false, storybook: { url: "http://localhost:6006" }, }, appium: { serverUrl: "https://hub.browserstack.com/wd/hub", reportToProvider: true, }, }, visualRegression: { threshold: 0.2, maxDiffPixelRatio: 0.01, baselinesDir: "./visual-baselines", }, hooks: { beforeAll: async ({ app }) => { /* global setup */ }, beforeEach: async ({ app }) => { /* reset state */ }, afterEach: async ({ app, result }) => { /* teardown */ }, afterAll: async ({ app, summary }) => { /* cleanup */ }, }, }); ``` ## `apps` Defines the app targets for each platform. ```ts apps: { web?: { url: string; appPath?: string }; android?: { packageName: string; appPath?: string }; ios?: { bundleId: string; appPath?: string; signing?: IOSSigningConfig }; } ``` | Field | Platform | Description | | ------------------------- | ----------- | --------------------------------------------------------- | | `web.url` | Web | Base URL Playwright navigates to on launch | | `android.packageName` | Android | Android application ID (e.g. `com.example.app`) | | `ios.bundleId` | iOS | iOS bundle identifier (e.g. `com.example.app`) | | `appPath` | Android/iOS | Path to `.app`, `.ipa`, or `.apk` for auto-install | | `signing.teamId` | iOS | Apple Development Team ID (required for physical devices) | | `signing.signingIdentity` | iOS | Code signing identity (default: `"Apple Development"`) | ## `platforms` ```ts platforms?: Array<"web" | "android" | "ios"> ``` Which platforms to run tests on by default. Can be overridden per-flow with `FlowConfig.platforms` and at the CLI with `--platform`. Default: `["web"]` ## `parallelPlatforms` ```ts parallelPlatforms?: boolean ``` Run platform groups concurrently instead of serially. Default: `false` This is most useful when your web, Android, and iOS runs use independent resources. CLI parallel controls such as `--parallel`, `--workers`, and `--devices` can still force concurrent execution for the selected run. ## `flowDir` ```ts flowDir?: string ``` Directory to discover flow files from. Accepts a glob or directory path. Default: `"./flows"` Relative paths are resolved from the directory that contains the config file, not from the current shell directory. ## `reporters` ```ts reporters?: string[] ``` One or more reporter names. Available reporters: | Name | Output | | --------- | ---------------------------------------------------- | | `console` | Human-readable terminal output (default) | | `json` | Structured JSON events to stdout | | `junit` | JUnit XML — compatible with CI artifact ingestion | | `html` | Self-contained HTML report with embedded screenshots | | `allure` | Allure-compatible result files | Default: `["console"]` ## `execution` Execution mode and remote Appium settings. ```ts execution?: { mode?: "local" | "appium"; web?: { browser?: "chromium" | "firefox" | "webkit"; headless?: boolean; storageState?: string; verboseLogging?: boolean; storybook?: { url?: string; iframePath?: string; }; }; appium?: { serverUrl?: string; capabilities?: Record; capabilitiesFile?: string; reportToProvider?: boolean; cloudProvider?: string; browserstack?: { app?: { id?: string; path?: string; name?: string; customId?: string }; local?: { enabled?: boolean; binary?: string; identifier?: string; args?: string[] }; options?: Record; }; saucelabs?: { app?: { id?: string; path?: string; name?: string }; connect?: { enabled?: boolean; binary?: string; tunnelName?: string; args?: string[] }; options?: Record; }; }; } ``` Use `execution.web` to configure the local Playwright runtime for web flows. | Field | Description | | ---------------------- | ------------------------------------------------------------------------ | | `browser` | Browser engine for local web runs: `chromium`, `firefox`, or `webkit` | | `headless` | Run Playwright without opening a visible browser window | | `storageState` | Preload Playwright cookies and storage state from a JSON file | | `verboseLogging` | Print verbose Playwright browser/page diagnostics to stdout | | `storybook.url` | Dedicated Storybook origin for `app.openStory()` / `Session.openStory()` | | `storybook.iframePath` | Override Storybook's preview iframe path, default `/iframe.html` | `storageState` is resolved relative to `spana.config.ts`. Storybook uses URLs instead of filesystem paths, so it stays portable by pointing at the right origin for each environment. Use `mode: "appium"` when running against BrowserStack, Sauce Labs, or another Appium-compatible grid. | Field | Description | | ----------------------------------- | ------------------------------------------------------------------------------ | | `serverUrl` | Remote Appium server URL | | `capabilities` / `capabilitiesFile` | Raw desired capabilities, with file paths resolved relative to the config file | | `reportToProvider` | Mark the remote session passed/failed when the provider supports it | | `cloudProvider` | Path to a custom cloud provider module that default-exports a `CloudProvider` | | `browserstack` | BrowserStack upload, local tunnel, and capability helper settings | | `saucelabs` | Sauce Labs upload, Sauce Connect, and capability helper settings | Raw capabilities from `execution.appium.capabilities`, `capabilitiesFile`, and `--caps-json` remain the strongest override surface. Provider helper sections fill in missing provider-specific fields and can manage BrowserStack Local / Sauce Connect lifecycle when enabled. For a custom provider implementation, see [Cloud Providers](/guides/cloud-providers/). ## CLI precedence For `spana test`, CLI flags win over config values. | CLI flag | Config field | | --------------------------------------------------------- | -------------------------------------- | | `--platform` | `platforms` | | `--reporter` | `reporters` | | `--retries` | `defaults.retries` | | `--workers` | `defaults.workers` | | `--driver` | `execution.mode` | | `--appium-url` | `execution.appium.serverUrl` | | `--validate-config` | Validates config and exits | | `--device` / `--devices` | CLI-only device selection | | `--parallel` | Enables concurrent execution | | `--watch` / `--changed` / `--last-failed` | CLI-only iteration controls | | `--update-baselines` | CLI-only visual regression control | | `--shard` / `--bail` | CLI-only execution controls | | `--debug-on-failure` / `--verbose` / `--quiet` / `--json` | CLI-only output and debugging controls | Sharding happens after tag/name/platform filtering so each shard gets a deterministic slice of the already-selected flows. ## `defaults` Timing and retry defaults applied to all auto-wait operations. Individual operations can override these with `WaitOptions`. ```ts defaults?: { waitTimeout?: number; // ms pollInterval?: number; // ms settleTimeout?: number; // ms retries?: number; waitForIdleTimeout?: number; typingDelay?: number; initialPollInterval?: number; hierarchyCacheTtl?: number; retryDelay?: number; workers?: number; } ``` | Option | Default | Description | | --------------------- | ------- | ------------------------------------------------------------- | | `waitTimeout` | `5000` | Maximum ms to wait for an assertion or element lookup | | `pollInterval` | `200` | Maximum ms between assertion polls | | `settleTimeout` | `0` | Stable time required before an assertion passes | | `retries` | `0` | Retry count for failed flow executions | | `waitForIdleTimeout` | `0` | Pause after mutating actions such as tap or scroll | | `typingDelay` | `0` | Delay between typed characters | | `initialPollInterval` | `50` | First poll interval before adaptive backoff ramps up | | `hierarchyCacheTtl` | `100` | Hierarchy cache freshness window in ms; set `0` to disable | | `retryDelay` | `0` | Delay between failed flow retry attempts | | `workers` | — | Default max workers per platform when `--parallel` is enabled | ## `artifacts` Controls screenshot and hierarchy capture on test completion. ```ts artifacts?: { outputDir?: string; captureOnFailure?: boolean; captureOnSuccess?: boolean; captureSteps?: boolean; screenshot?: boolean; uiHierarchy?: boolean; consoleLogs?: boolean; jsErrors?: boolean; har?: boolean; } ``` | Option | Default | Description | | ------------------ | ------------------ | ------------------------------------------------- | | `outputDir` | `"./spana-output"` | Directory to write captured artifacts | | `captureOnFailure` | `true` | Capture artifacts for failed flows | | `captureOnSuccess` | `false` | Capture final artifacts for passed flows | | `captureSteps` | `false` | Capture screenshots after each recorded step | | `screenshot` | `true` | Include screenshots in captures | | `uiHierarchy` | `true` | Include UI hierarchy dumps | | `consoleLogs` | `true` | Include captured browser console logs on web | | `jsErrors` | `true` | Include uncaught browser JavaScript errors on web | | `har` | `true` | Include HAR network traces on web | ## `hooks` Lifecycle hooks that run around flow execution. Each hook receives a `HookContext`. ```ts hooks?: { beforeAll?: (ctx: HookContext) => Promise; beforeEach?: (ctx: HookContext) => Promise; afterEach?: (ctx: HookContext) => Promise; afterAll?: (ctx: HookContext) => Promise; } ``` | Hook | When it runs | | ------------ | --------------------------------------------------------- | | `beforeAll` | Once before all flows on a platform | | `beforeEach` | Before each individual flow | | `afterEach` | After each individual flow (always runs, even on failure) | | `afterAll` | Once after all flows on a platform | `HookContext` provides `app`, `expect`, `platform`, `result` (in `afterEach`), and `summary` (in `afterAll`). ### Error handling | Hook | On failure | | ------------ | ----------------------------------------------------------- | | `beforeAll` | All flows on that platform are skipped and marked as failed | | `beforeEach` | That flow is skipped and marked as failed | | `afterEach` | Warning logged, test result is not affected | | `afterAll` | Warning logged, test results are not affected | ### Example ```ts export default defineConfig({ hooks: { beforeEach: async ({ app }) => { await app.launch({ clearState: true }); }, afterEach: async ({ app, result }) => { if (result?.status === "failed") { console.log(`Flow failed: ${result.name}`); } }, }, }); ``` ## Per-flow configuration The `flow()` function accepts an optional config object as its second argument, letting you override global settings for a single flow. ```ts import { flow } from "spana-test"; flow( "checkout", { timeout: 30000, tags: ["smoke"], artifacts: { captureSteps: true }, launchOptions: { deepLink: "myapp://checkout" }, }, async ({ app }) => { // ... }, ); ``` ```ts interface FlowConfig { tags?: string[]; platforms?: Array<"web" | "android" | "ios">; timeout?: number; autoLaunch?: boolean; launchOptions?: LaunchOptions; artifacts?: ArtifactConfig; defaults?: FlowDefaults; when?: WhenCondition; } ``` | Option | Default | Description | | --------------- | ------- | ------------------------------------------------------------------- | | `tags` | `[]` | Tags for CLI filtering with `--tag` | | `platforms` | — | Restrict a flow to specific platforms | | `timeout` | — | Overall flow timeout in ms | | `autoLaunch` | `true` | Automatically launch the app before the flow starts | | `launchOptions` | — | Per-flow launch defaults merged on top of project `launchOptions` | | `artifacts` | — | Per-flow artifact overrides | | `defaults` | — | Per-flow wait, typing, cache, and idle timing overrides | | `when` | — | Runtime conditions such as `platform` or environment-variable gates | The per-flow `artifacts` object is merged with the global `artifacts` config, so you only need to specify the fields you want to override. For example, enabling `captureSteps` on a single flow: ```ts flow( "visual regression", { artifacts: { captureSteps: true, captureOnSuccess: true } }, async ({ app }) => { // Every step is captured, and the final state is saved even on success }, ); ``` ## `launchOptions` Default launch options applied to each flow launch. `FlowConfig.launchOptions` overrides these defaults for one flow, and explicit `app.launch(opts)` calls are merged on top of both. ```ts launchOptions?: LaunchOptions ``` ```ts export default defineConfig({ launchOptions: { clearState: true, // fresh state every run }, }); ``` ### `LaunchOptions` reference ```ts interface LaunchOptions { clearState?: boolean; clearKeychain?: boolean; deepLink?: string; launchArguments?: Record; deviceState?: DeviceStateConfig; } interface DeviceStateConfig { language?: string; locale?: string; timeZone?: string; } ``` | Option | Default | Description | | ----------------- | ------- | ------------------------------------------------------------------------------------ | | `clearState` | `false` | Clear app data/storage before launch | | `clearKeychain` | `false` | Clear the iOS keychain before launch (simulator only) | | `deepLink` | — | Open the app via a deep link URL | | `launchArguments` | — | Key-value pairs passed as launch arguments to the app | | `deviceState` | — | Launch-time language / locale / time-zone overrides where the runtime can honor them | #### Platform behavior | Option | Web | Android | iOS | | ----------------- | ---------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------- | | `clearState` | Clears cookies, localStorage | `adb shell pm clear` | Resets app permissions | | `clearKeychain` | No-op | No-op (warns) | `xcrun simctl keychain reset` | | `launchArguments` | No-op | Passed as `--es` extras via `am start` | Appium iOS: process args via `mobile: launchApp`; local WDA: warns + ignores | | `deviceState` | Warns + ignores | Appium: session-start caps; local Android: warns + ignores | Appium: session caps + launch-time process config; local WDA: warns + ignores | | `deepLink` | Navigates to URL | `adb shell am start -d ` | `xcrun simctl openurl` / WDA | Android `launchArguments` are string extras. For example: ```ts await app.launch({ launchArguments: { featureFlag: "on", buildVariant: "staging", }, }); ``` `deviceState` is for launch-time localization and time-zone setup. It does **not** mutate the device clock mid-run. In Appium mode, suite-level `launchOptions.deviceState` is also mapped into session capabilities so defaults apply even when Appium keeps `autoLaunch` off. Common locale forms such as `fr_CA` / `fr-CA` are normalized for Appium, but Android still needs both language and region information available. #### Per-flow usage Use `FlowConfig.launchOptions` when one flow needs a different launch profile than the project defaults: ```ts flow( "checkout in French", { autoLaunch: true, launchOptions: { clearState: true, deepLink: "myapp://checkout", deviceState: { language: "fr", locale: "fr_CA", timeZone: "America/Toronto", }, }, }, async ({ app }) => { // ... }, ); ``` When `autoLaunch` is `false`, you can still call `app.launch()` manually. The project and per-flow defaults are merged first, then the manual call wins: ```ts flow("onboarding", { autoLaunch: false }, async ({ app }) => { await app.launch({ deepLink: "myapp://welcome" }); // ... }); ``` ## `visualRegression` Project-level defaults for screenshot assertions. ```ts visualRegression?: { threshold?: number; maxDiffPixelRatio?: number; baselinesDir?: string; } ``` | Option | Default | Description | | ------------------- | -------------------------------------- | --------------------------------------------------- | | `threshold` | `0.2` | Pixel comparison sensitivity | | `maxDiffPixelRatio` | `0.01` | Maximum differing pixels before the assertion fails | | `baselinesDir` | `__baselines__` next to each flow file | Centralize baseline screenshots in one directory | These values become defaults for `expect(selector).toMatchScreenshot(name, options?)`. Per-assertion options still win, and baseline rewrites are still controlled by `spana test --update-baselines`. --- ## Flows A flow is the basic unit of a spana test. Each flow file exports a single `FlowDefinition` as its default export. ## Defining a flow `flow()` has two overloads: ```ts // Without config flow(name: string, fn: FlowFn): FlowDefinition // With config flow(name: string, config: FlowConfig, fn: FlowFn): FlowDefinition ``` ### Basic flow ```ts import { flow } from "spana-test"; export default flow("user can log in", async ({ app, expect }) => { await app.tap({ testID: "email-input" }); await app.inputText("user@example.com"); await app.tap({ testID: "login-button" }); await expect({ testID: "home-screen" }).toBeVisible(); }); ``` ### Flow with config ```ts export default flow( "checkout flow", { tags: ["smoke", "payments"], platforms: ["android", "ios"], timeout: 60000, autoLaunch: true, launchOptions: { deepLink: "myapp://checkout", }, }, async ({ app, expect, platform }) => { // ... }, ); ``` ## FlowContext The function receives a `FlowContext` object: ```ts interface FlowContext { app: PromiseApp; expect: (selector: Selector) => PromiseExpectation; platform: Platform; } ``` | Property | Type | Description | | ---------- | ---------------------------------- | --------------------------------------------------------- | | `app` | `PromiseApp` | App interaction API — tap, type, scroll, launch, etc. | | `expect` | `(selector) => PromiseExpectation` | Assertion API — `toBeVisible`, `toBeHidden`, `toHaveText` | | `platform` | `"web" \| "android" \| "ios"` | The platform this run is executing on | ## FlowConfig ```ts interface FlowConfig { tags?: string[]; platforms?: Platform[]; timeout?: number; autoLaunch?: boolean; launchOptions?: LaunchOptions; artifacts?: ArtifactConfig; defaults?: FlowDefaults; when?: WhenCondition; } interface WhenCondition { platform?: Platform | Platform[]; env?: string; } ``` | Option | Type | Default | Description | | --------------- | ---------------- | -------------- | ---------------------------------------------------------------- | | `tags` | `string[]` | — | Tag strings for `--tag` filtering at the CLI | | `platforms` | `Platform[]` | all configured | Restrict this flow to specific platforms only | | `timeout` | `number` | config default | Flow-level timeout in milliseconds | | `autoLaunch` | `boolean` | `true` | Automatically launch the app before the flow starts | | `launchOptions` | `LaunchOptions` | config default | Override launch defaults for this flow and for manual app.launch | | `artifacts` | `ArtifactConfig` | config default | Override capture behavior for this single flow | | `defaults` | `FlowDefaults` | config default | Override wait / typing / stability defaults per flow | | `when` | `WhenCondition` | — | Runtime conditions that control whether the flow runs | ### Per-flow launch overrides `FlowConfig.launchOptions` is merged on top of the project `launchOptions`, and explicit `app.launch(opts)` calls are merged last. ```ts export default flow( "launch in French", { autoLaunch: true, launchOptions: { deepLink: "myapp://checkout", deviceState: { language: "fr", locale: "fr_CA", }, }, }, async ({ expect }) => { await expect({ testID: "checkout-screen" }).toBeVisible(); }, ); ``` ### Conditional execution with `when` The `when` field lets you skip flows based on runtime conditions. #### Platform condition `when.platform` works like `platforms` but within the `when` block, keeping conditional logic grouped: ```ts export default flow("iOS-specific test", { when: { platform: "ios" } }, async ({ app, expect }) => { // only runs on iOS }); ``` You can also pass an array: ```ts export default flow( "mobile-only test", { when: { platform: ["ios", "android"] } }, async ({ app, expect }) => { // runs on iOS and Android, skipped on web }, ); ``` #### Environment variable condition `when.env` skips the flow unless the specified environment variable is set: ```ts export default flow( "CI smoke test", { when: { env: "CI" }, tags: ["smoke"], }, async ({ app, expect }) => { // only runs when CI=1 (or any truthy value) }, ); ``` ## The `app` API All methods return `Promise` unless noted. ### Core interaction | Method | Signature | Description | | -------------------- | ------------------------------------- | ------------------------------------------------ | | `tap` | `(selector, opts?) => Promise` | Tap an element | | `tapXY` | `(x, y) => Promise` | Tap at absolute coordinates | | `doubleTap` | `(selector, opts?) => Promise` | Double-tap an element | | `longPress` | `(selector, opts?) => Promise` | Long-press an element | | `longPressXY` | `(x, y, opts?) => Promise` | Long-press at coordinates | | `inputText` | `(text) => Promise` | Type text into the focused element | | `pressKey` | `(key) => Promise` | Press a named key | | `hideKeyboard` | `() => Promise` | Dismiss the software keyboard | | `dismissKeyboard` | `(opts?) => Promise` | Use a platform-aware keyboard dismissal strategy | | `swipe` | `(direction, opts?) => Promise` | Swipe in a direction | | `scroll` | `(direction) => Promise` | Scroll in a direction | | `scrollUntilVisible` | `(selector, opts?) => Promise` | Scroll until a target becomes visible | | `backUntilVisible` | `(selector, opts?) => Promise` | Use system back until a target becomes visible | Direction values are `"up" | "down" | "left" | "right"`. `dismissKeyboard()` defaults to an auto strategy that uses the driver-specific keyboard dismissal path and falls back to Android system back when needed. `scrollUntilVisible()` and `backUntilVisible()` are useful for replacing ad hoc retry loops in mobile-heavy flows. ### Advanced gestures | Method | Signature | Description | | ------------ | ----------------------------------------------------- | ------------------------------------- | | `pinch` | `(selector, { scale?, duration? }?) => Promise` | Perform a pinch gesture on an element | | `zoom` | `(selector, { scale?, duration? }?) => Promise` | Perform a zoom gesture on an element | | `multiTouch` | `(sequences) => Promise` | Run multiple touch sequences together | These gestures are only available on mobile runtimes. Use them for map canvases, image viewers, and multi-finger interactions that are awkward to model with repeated taps. ### App lifecycle and navigation | Method | Signature | Description | | ------------ | -------------------------------------- | ----------------------------------------------------- | | `launch` | `(opts?) => Promise` | Launch the app, optionally with a deep link | | `stop` | `() => Promise` | Stop the app | | `kill` | `() => Promise` | Force-kill the app | | `clearState` | `() => Promise` | Clear app data/state | | `openLink` | `(url) => Promise` | Open a URL or deep link | | `openStory` | `(storyId, options?) => Promise` | Open a Storybook story inside the web runtime | | `back` | `() => Promise` | Press the Android back button or browser history back | `openStory()` is web-only. It uses `execution.web.storybook` when configured and falls back to `apps.web.url` plus Storybook's `iframe.html`. ### Element queries and utilities | Method | Signature | Description | | ---------------- | ---------------------------------------------------- | ------------------------------------------------ | | `takeScreenshot` | `() => Promise` | Capture a screenshot and return the bytes | | `getText` | `(selector, opts?) => Promise` | Read the current element text | | `getAttribute` | `(selector, name, opts?) => Promise` | Read an element attribute | | `isVisible` | `(selector, opts?) => Promise` | Check visibility without failing the flow | | `isEnabled` | `(selector, opts?) => Promise` | Check whether an element is enabled | | `evaluate` | `(fn \| string, ...args) => Promise` | Run JavaScript in the browser context (web only) | `getText()`, `getAttribute()`, `isVisible()`, and `isEnabled()` are useful when you need branching logic instead of a hard assertion. ### Browser runtime helpers | Method | Signature | Description | | ---------------------- | -------------------------------------------------- | -------------------------------------------------------------------------- | | `mockNetwork` | `(matcher, response) => Promise` | Fulfill matching requests with a mocked response | | `blockNetwork` | `(matcher) => Promise` | Abort matching requests | | `clearNetworkMocks` | `() => Promise` | Remove active route mocks or blocks | | `setNetworkConditions` | `(conditions) => Promise` | Simulate network conditions — profiles, custom throttling, or offline mode | | `saveCookies` | `(path) => Promise` | Save Playwright cookies to a JSON file | | `loadCookies` | `(path) => Promise` | Load cookies from a JSON file | | `saveAuthState` | `(path) => Promise` | Save Playwright storage state to disk | | `loadAuthState` | `(path) => Promise` | Replace the browser context with saved auth state | | `downloadFile` | `(path) => Promise` | Save the next browser download to disk | | `uploadFile` | `(selector, path) => Promise` | Upload a local file through a file input | | `newTab` | `(url?) => Promise` | Open a new browser tab | | `switchToTab` | `(index) => Promise` | Switch to a tab by index | | `closeTab` | `() => Promise` | Close the current tab | | `getTabIds` | `() => Promise` | List known browser tab IDs | | `getConsoleLogs` | `() => Promise>` | Read captured browser console messages | | `getJSErrors` | `() => Promise>` | Read captured uncaught JavaScript errors | | `getHAR` | `() => Promise>` | Read the recorded HTTP Archive for the current run | These helpers are available on local Playwright web runs. When artifact capture is enabled, failures can also write console logs, JavaScript errors, and HAR files into `spana-output/`. #### `setNetworkConditions()` Simulate degraded or offline network conditions across all platforms. You can use a named profile or supply custom values. **Available profiles:** `wifi`, `4g`, `3g`, `2g`, `edge`, `offline` ```ts // Simulate 3G network await app.setNetworkConditions({ profile: "3g" }); // Go offline await app.setNetworkConditions({ profile: "offline" }); // Back to normal await app.setNetworkConditions({ profile: "wifi" }); ``` Custom values still work when you need fine-grained control: ```ts await app.setNetworkConditions({ latencyMs: 150, downloadThroughputKbps: 1000, uploadThroughputKbps: 500, }); ``` **Platform support:** | Platform | Offline | Profiles | Custom Values | | -------------------- | ------- | ---------- | ------------- | | Web (Chromium) | Yes | Yes | Yes | | Web (Firefox/WebKit) | Yes | No | No | | Android emulator | Yes | Yes | Yes | | Android device | Yes | No | No | | iOS simulator | Yes | Yes (sudo) | Yes (sudo) | | Appium cloud | Yes | Yes | varies | ```ts flow("web app can run with mocked APIs", async ({ app, platform }) => { if (platform !== "web") return; await app.loadAuthState("./auth/user.json"); await app.mockNetwork("**/api/profile", { json: { id: "demo", name: "Demo User" }, }); await app.blockNetwork("**/analytics/**"); await app.setNetworkConditions({ profile: "3g" }); await app.evaluate(() => console.info("profile hydrated")); const logs = await app.getConsoleLogs(); const jsErrors = await app.getJSErrors(); const har = await app.getHAR(); if (!logs.some((entry) => entry.text.includes("profile hydrated"))) { throw new Error("Expected the profile hydration log to be captured."); } if (jsErrors.length > 0) { throw new Error(`Unexpected JS errors: ${jsErrors.map((entry) => entry.message).join(", ")}`); } if (!Array.isArray((har as { log?: { entries?: unknown[] } }).log?.entries)) { throw new Error("Expected HAR output to contain request entries."); } await app.saveCookies("./tmp/cookies.json"); }); ``` ### Storybook-backed component flows Storybook is a good isolated surface for Spana's web runtime when you want component-level checks without giving up real-browser automation. ```ts flow("primary button story passes smoke checks", async ({ app, expect, platform }) => { if (platform !== "web") return; await app.openStory("components-button--primary", { args: { label: "Save", disabled: false }, globals: { theme: "dark" }, }); await expect({ role: "button", text: "Save" }).toBeVisible(); await expect({ role: "button", text: "Save" }).toMatchScreenshot("storybook-button"); }); ``` Set `execution.web.storybook.url` when Storybook runs on a different origin from your main app. `args` and `globals` support scalar values (`string`, `number`, `boolean`, `null`). ### Hybrid / WebView helpers | Method | Signature | Description | | ------------------- | ------------------------------ | ------------------------------------------ | | `getContexts` | `() => Promise` | List available native and WebView contexts | | `getCurrentContext` | `() => Promise` | Read the currently active context | | `switchToContext` | `(contextId) => Promise` | Switch to a specific context ID | | `switchToWebView` | `() => Promise` | Switch to the first available WebView | | `switchToNativeApp` | `() => Promise` | Switch back to the native app context | These helpers are useful for hybrid apps where you need to move between native chrome and embedded web content. ### JavaScript execution `app.evaluate()` runs JavaScript inside the browser page context. Use it to read DOM state, manipulate local storage, or access browser-only globals. ```ts flow("read page state", async ({ app, platform }) => { if (platform !== "web") return; const title = await app.evaluate(() => document.title); const count = await app.evaluate( (selector: string) => document.querySelectorAll(selector).length, "button", ); await app.evaluate(() => { localStorage.setItem("feature-flag", "true"); }); if (!title || count === 0) { throw new Error("Expected page state to be readable from evaluate()."); } }); ``` `evaluate()` is only supported on the web platform. Native apps do not expose a JavaScript execution context. ## Per-flow artifact overrides Use `artifacts` in `FlowConfig` when one flow needs different capture behavior from the global defaults. ```ts export default flow( "checkout keeps extra diagnostics on success", { artifacts: { captureSteps: true, captureOnSuccess: true, consoleLogs: true, jsErrors: true, har: true, }, }, async ({ app, expect, platform }) => { if (platform === "web") { await app.openLink("/checkout"); } await expect({ text: "Checkout" }).toBeVisible(); }, ); ``` Use the global config in [Configuration](/getting-started/configuration/) for your default policy, then tighten or loosen capture per flow only where it helps debugging. ## Settings export You can export named `settings` from a flow file to apply shared config to all flows in that file: ```ts export const settings = { tags: ["smoke"], timeout: 30000, }; export default flow("my flow", async ({ app }) => { // ... }); ``` Per-flow `FlowConfig` values take precedence over `settings`. --- ## Selectors A selector tells spana which element to interact with or assert on. Selectors are used by all `app` interaction methods and `expect()`. ## Selector types ### testID (recommended) ```ts { testID: "login-button"; } ``` The preferred selector. Maps to the platform's primary element identifier: | Platform | Attribute | | -------- | ------------------------------------ | | Web | `data-testid` attribute | | Android | `resource-id` (last segment matched) | | iOS | `accessibilityIdentifier` | Add `testID` props to your React Native components: ```tsx Sign In ``` On web, this renders as `data-testid="login-button"`. ### text ```ts { text: "Sign In"; } ``` Matches against the visible label text of an element. Partial matching is supported — the element text only needs to contain the provided string. Use this when a `testID` is not available, such as for dynamic or third-party content. ### accessibilityLabel ```ts { accessibilityLabel: "Close dialog"; } ``` Matches the OS-level accessibility label. Useful for elements that have a label distinct from their visible text (e.g. icon buttons). ### point ```ts { point: { x: 150, y: 340 } } ``` Taps at absolute screen coordinates. Use as a last resort — coordinates are device-specific and break across screen sizes. ### String shorthand A plain string is treated as a `testID`: ```ts await app.tap("login-button"); // equivalent to: await app.tap({ testID: "login-button" }); ``` ## Relative selectors When multiple elements match the same selector, use relative positioning to disambiguate. A relative selector wraps a base selector with directional constraints: ```ts // Tap the "Edit" button below the "Email" label await app.tap({ selector: { text: "Edit" }, below: { text: "Email" } }); // Tap the button to the right of the "Username" label await app.tap({ selector: { testID: "action-btn" }, rightOf: { text: "Username" } }); // Find an element inside a specific container await app.tap({ selector: { text: "Submit" }, childOf: { testID: "login-form" } }); ``` | Constraint | Description | | ---------- | --------------------------------------------------- | | `below` | Element must be below the anchor (closest first) | | `above` | Element must be above the anchor (closest first) | | `leftOf` | Element must be left of the anchor (closest first) | | `rightOf` | Element must be right of the anchor (closest first) | | `childOf` | Element must be a descendant of the anchor | Constraints can be combined — all must match: ```ts // Button below the header AND to the right of the label await app.tap({ selector: { testID: "btn" }, below: { text: "Header" }, rightOf: { text: "Label" }, }); ``` Relative selectors work with all interaction methods (`tap`, `doubleTap`, `longPress`) and assertions (`expect().toBeVisible()`, etc.). ## Selector priority When spana builds a suggested selector (e.g. in `spana selectors` output), it uses this priority: 1. `testID` — most stable, preferred 2. `accessibilityLabel` 3. `text` 4. `point` — last resort ## WaitOptions All selector-based methods accept an optional `WaitOptions` object to override the global defaults for that specific call: ```ts await app.tap({ testID: "slow-element" }, { timeout: 10000 }); await expect({ testID: "result" }).toBeVisible({ timeout: 15000, pollInterval: 500 }); ``` | Option | Type | Description | | --------------- | -------- | --------------------------------------------- | | `timeout` | `number` | ms to wait before failing | | `pollInterval` | `number` | ms between hierarchy polls | | `settleTimeout` | `number` | ms the element must be stable before matching | --- ## Assertions Assertions are made with the `expect` function from `FlowContext`. It takes a selector and returns a `PromiseExpectation` with chainable assertion methods. ```ts const { expect } = ctx; await expect({ testID: "welcome-banner" }).toBeVisible(); ``` ## API ### `expect(selector)` ```ts expect: (selector: Selector) => PromiseExpectation; ``` Returns a `PromiseExpectation` bound to the given selector. ### Core visibility, text, and state assertions | Method | Signature | Description | | ----------------- | --------------------------------------------------------------------- | -------------------------------------------------- | | `toBeVisible` | `(opts?: WaitOptions) => Promise` | Assert that the element exists and is visible | | `toBeHidden` | `(opts?: WaitOptions) => Promise` | Assert that the element is missing or hidden | | `toHaveText` | `(expected: string, opts?: WaitOptions) => Promise` | Assert an exact text match | | `toContainText` | `(expected: string, opts?: WaitOptions) => Promise` | Assert a case-insensitive substring match | | `toMatchText` | `(pattern: RegExp, opts?: WaitOptions) => Promise` | Assert a regular-expression text match | | `toHaveValue` | `(expected: string \| number, opts?: WaitOptions) => Promise` | Assert an exact form value match | | `toHaveAttribute` | `(name: string, value?: string, opts?: WaitOptions) => Promise` | Assert that an attribute exists or matches a value | | `toBeEnabled` | `(opts?: WaitOptions) => Promise` | Assert that the element is enabled | | `toBeDisabled` | `(opts?: WaitOptions) => Promise` | Assert that the element is disabled | ```ts await expect({ testID: "success-message" }).toBeVisible(); await expect({ text: "Welcome" }).toBeVisible({ timeout: 8000 }); await expect({ testID: "user-greeting" }).toHaveText("Hello, Alice"); await expect({ role: "status" }).toContainText("saved"); await expect({ testID: "price" }).toMatchText(/^\$\d+\.\d{2}$/); await expect({ testID: "email" }).toHaveValue("demo@example.com"); await expect({ testID: "primary-button" }).toHaveAttribute("aria-busy", "false"); await expect({ testID: "submit" }).toBeEnabled(); ``` Use `toHaveText()` for exact text, `toContainText()` for partial copy, and `toMatchText()` when you need more flexible matching. ### Visual regression ```ts toMatchScreenshot( name: string, options?: { threshold?: number; maxDiffPixelRatio?: number; }, ): Promise ``` Capture the current element and compare it against a named baseline image. ```ts await expect({ testID: "avatar" }).toMatchScreenshot("profile-avatar"); await expect({ testID: "receipt" }).toMatchScreenshot("receipt", { threshold: 0.2, maxDiffPixelRatio: 0.01, }); ``` Create or refresh baselines with `spana test --update-baselines`. For suite-wide defaults, configure `visualRegression` in `spana.config.ts`. ### Accessibility assertions | Method | Signature | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `toPassAccessibilityAudit` | `(options?: { severity?: "critical" \| "serious" \| "moderate" \| "minor"; rules?: string[]; exclude?: Selector[] }) => Promise` | Run an axe-core audit of the current web page | | `toHaveAccessibilityLabel` | `(expected?: string) => Promise` | Assert that an element has an accessibility label, optionally with an exact value | | `toBeFocusable` | `() => Promise` | Assert that the element can receive focus | | `toHaveRole` | `(expected: string) => Promise` | Assert a semantic role such as `button` or `link` | | `toHaveMinTouchTarget` | `(size?: number) => Promise` | Assert a minimum touch target size, default `44` | ```ts await expect("body").toPassAccessibilityAudit({ severity: "serious", rules: ["color-contrast", "button-name"], }); await expect({ testID: "login-button" }).toHaveAccessibilityLabel("Log in"); await expect({ testID: "login-button" }).toHaveRole("button"); await expect({ testID: "login-button" }).toBeFocusable(); await expect({ testID: "login-button" }).toHaveMinTouchTarget(48); ``` `toPassAccessibilityAudit()` is web-only. The other accessibility assertions are element-level checks that work across supported platforms. ## Auto-wait behavior All assertions auto-wait. spana does not require manual `sleep()` calls. The assertion loop works as follows: 1. Dump the element hierarchy from the platform driver. 2. Search the tree for the selector. 3. Check the assertion condition. 4. If the condition is not met, wait and retry using adaptive polling. 5. If `timeout` is exceeded, fail with a descriptive error including the selector and last known state. `WaitOptions` lets you tune assertion behavior: ```ts type WaitOptions = { timeout?: number; pollInterval?: number; initialPollInterval?: number; settleTimeout?: number; }; ``` - `timeout`: maximum time to wait before failing - `pollInterval`: maximum poll interval once backoff ramps up - `initialPollInterval`: first poll interval before backoff grows - `settleTimeout`: how long the condition must remain stable before passing `settleTimeout` is useful for transitions and animations where the element briefly appears and disappears. ## Timeout configuration Timeouts are resolved in this order (highest priority first): 1. `opts.timeout` passed directly to the assertion method 2. `flow(..., { defaults: { waitTimeout } })` on the containing flow 3. `defaults.waitTimeout` in `spana.config.ts` 4. Built-in default: 5000 ms ```ts // Global default in config export default defineConfig({ defaults: { waitTimeout: 8000 }, }); // Per-flow override for waits and polling export default flow( "slow screen test", { defaults: { waitTimeout: 12000, pollInterval: 250, settleTimeout: 300, }, }, async ({ expect }) => { // Per-assertion override await expect({ testID: "result" }).toBeVisible({ timeout: 15000 }); }, ); ``` `FlowConfig.timeout` is a separate overall flow timeout. It does not replace assertion wait settings. --- ## Platform-Specific Tests spana runs a single flow file against multiple platforms. There are two mechanisms for platform-specific behavior: branching inside a flow, and restricting a flow to specific platforms entirely. ## Branching inside a flow The `platform` value in `FlowContext` is `"web" | "android" | "ios"`. Use it for conditional logic within a flow that is mostly shared across platforms. ```ts import { flow } from "spana-test"; export default flow("user can share content", async ({ app, expect, platform }) => { await app.tap({ testID: "share-button" }); if (platform === "ios") { // iOS share sheet uses a native action sheet await expect({ text: "Copy Link" }).toBeVisible(); await app.tap({ text: "Copy Link" }); } else if (platform === "android") { // Android uses the system share dialog await expect({ text: "Copy to clipboard" }).toBeVisible(); await app.tap({ text: "Copy to clipboard" }); } else { // Web uses a custom share modal await expect({ testID: "share-modal" }).toBeVisible(); await app.tap({ testID: "copy-link" }); } await expect({ testID: "share-confirmation" }).toBeVisible(); }); ``` ## Restricting a flow to specific platforms Use `FlowConfig.platforms` to prevent a flow from running on platforms where it does not apply. ```ts import { flow } from "spana-test"; export default flow( "push notification permissions", { platforms: ["android", "ios"] }, async ({ app, expect }) => { await app.tap({ testID: "enable-notifications" }); await expect({ testID: "permission-granted" }).toBeVisible(); }, ); ``` This flow is skipped entirely when the runner targets `web`. ## CLI platform filtering Regardless of per-flow `platforms` config, you can also filter at the CLI: ```bash # Run only on web spana test --platform web # Run on android and ios only spana test --platform android,ios ``` CLI filtering takes effect before per-flow filtering. A flow with `platforms: ["android"]` will not run if you pass `--platform web`, even if both are in your config. ## Common patterns ### Platform-specific selectors Some elements have the same semantic purpose but different identifiers across platforms. Assign the selector based on platform: ```ts export default flow("open menu", async ({ app, platform }) => { const menuSelector = platform === "ios" ? { accessibilityLabel: "Main menu" } : { testID: "menu-button" }; await app.tap(menuSelector); }); ``` ### Skip web for native-only features ```ts export default flow( "biometric authentication", { platforms: ["ios", "android"] }, async ({ app, expect }) => { await app.tap({ testID: "use-biometrics" }); await expect({ testID: "biometric-success" }).toBeVisible({ timeout: 10000 }); }, ); ``` ### Deep link only on mobile ```ts export default flow("deep link navigation", async ({ app, platform }) => { if (platform !== "web") { await app.openLink("myapp://profile/settings"); } else { await app.tap({ testID: "settings-nav" }); } await expect({ testID: "settings-screen" }).toBeVisible(); }); ``` --- ## Gherkin / BDD Spana supports Gherkin-style BDD tests alongside the standard flow API. Write human-readable `.feature` files, then implement step definitions in TypeScript. ## Project structure ``` flows/ login/ login.feature # Gherkin scenarios steps/ login.steps.ts # Step definitions dashboard.flow.ts # Standard flow (both styles coexist) ``` Step files must live in a `steps/` subdirectory next to the `.feature` file. Spana auto-discovers and loads them. ## Writing a feature file ```gherkin title="flows/login/login.feature" @e2e @auth Feature: User login Background: Given I am on the login screen @smoke @web @android @ios Scenario: Successful login When I enter "user@example.com" in the email field And I enter "password123" in the password field And I tap the login button Then I should see the text "Welcome" @web @android Scenario Outline: Navigate to When I navigate to "" Then I should see the element "" Examples: | page | path | selector | | dashboard | /dash | dash-title | | settings | /settings | settings-title| ``` ### Tags as platform filters Tags like `@web`, `@android`, and `@ios` on a scenario control which platforms it runs on. Other tags (like `@smoke`, `@e2e`) can be used with `--tag` to filter runs. ### Background `Background` steps run before every scenario in the feature, similar to a `beforeEach` hook. ### Scenario Outline Use `Scenario Outline` with an `Examples` table to run the same scenario with different data. Placeholders like `` are replaced with values from each row. ## Writing step definitions Step definitions map Gherkin steps to TypeScript functions. Import them from `spana-test/steps`: ```ts title="flows/login/steps/login.steps.ts" import { Given, When, Then } from "spana-test/steps"; Given("I am on the login screen", async ({ app }) => { await app.launch({ deepLink: "myapp://login" }); }); When("I enter {string} in the email field", async ({ app }, email) => { await app.tap({ testID: "email-input" }); await app.inputText(email as string); }); When("I enter {string} in the password field", async ({ app }, password) => { await app.tap({ testID: "password-input" }); await app.inputText(password as string); }); When("I tap the login button", async ({ app }) => { await app.tap({ testID: "login-button" }); }); Then("I should see the text {string}", async ({ expect }, text) => { await expect({ text: text as string }).toBeVisible(); }); Then("I should see the element {string}", async ({ expect }, testID) => { await expect({ testID: testID as string }).toBeVisible(); }); ``` ### Step keywords | Function | Purpose | | -------- | ----------------------------- | | `Given` | Set up preconditions | | `When` | Perform actions | | `Then` | Assert outcomes | | `And` | Continue the previous keyword | | `But` | Negative continuation | All five register steps the same way -- the keyword is for readability. `And` and `But` inherit the type of the preceding step. ### Pattern matching Step patterns support two forms: **String patterns** with `{string}`, `{int}`, and `{float}` placeholders: ```ts Then("I should see the element {string} within {int}ms", async ({ expect }, testID, timeout) => { await expect({ testID: testID as string }).toBeVisible({ timeout: timeout as number }); }); ``` **Regular expressions** for complex matching: ```ts When(/^I swipe (left|right|up|down)$/, async ({ app }, direction) => { await app.swipe(direction as string); }); ``` Captured groups are passed as additional arguments after the context. ### Step context Every step function receives the same context available in standard flows: | Property | Description | | ---------- | ---------------------------------------------------- | | `app` | Full `PromiseApp` API (tap, inputText, scroll, etc.) | | `expect` | Assertion helper | | `platform` | Current platform (`"web"`, `"android"`, `"ios"`) | | `config` | Resolved config object | ## Hooks Run setup/teardown code before or after each scenario: ```ts import { Before, After } from "spana-test/steps"; // Runs before every scenario Before(async ({ app }) => { await app.launch(); }); // Runs after every scenario After(async ({ app }) => { await app.takeScreenshot("after-scenario"); }); ``` ### Tag-filtered hooks Restrict hooks to scenarios with specific tags: ```ts // Only runs before scenarios tagged @auth Before("@auth", async ({ app }) => { await app.launch({ deepLink: "myapp://login" }); }); ``` ## World (shared state) Use `defineWorld` to share state and helper methods across steps within a scenario: ```ts title="flows/login/steps/world.ts" import { defineWorld } from "spana-test/steps"; export default defineWorld({ // Fresh state for each scenario create: () => ({ currentUser: "", authToken: "", }), // Helper methods available in step context methods: (ctx) => ({ async loginAs(email: string, password: string) { await ctx.app.tap({ testID: "email-input" }); await ctx.app.inputText(email); await ctx.app.tap({ testID: "password-input" }); await ctx.app.inputText(password); await ctx.app.tap({ testID: "login-button" }); ctx.currentUser = email; }, }), }); ``` World state is created fresh for each scenario. The `state` map is also available for arbitrary key-value storage across steps. ## Running Gherkin tests Gherkin tests run with the same CLI as standard flows: ```bash # Run all tests (flows + features) spana test # Filter by tag spana test --tag @smoke # Filter by name spana test --grep "login" # Run only on specific platforms spana test --platform web,android ``` ## Mixing flows and features Both `.flow.ts` and `.feature` files can live in the same `flowDir`. Spana discovers and runs both. Use whichever style fits the test -- Gherkin for behavior specs, flows for lower-level or exploratory tests. --- ## CLI Commands The `spana` binary is the entry point for running flows, validating projects, inspecting live UI state, and scaffolding new tests. ## `spana test` Run discovered flows or a specific file. ```bash spana test [path] [options] ``` `path` is optional. If omitted, Spana discovers flows from `flowDir` in `spana.config.ts`. ### Filtering and targeting | Flag | Description | | ------------------------------ | -------------------------------------------- | | `--platform ` | Restrict the run to one or more platforms | | `--tag ` | Run only flows with matching tags | | `--grep ` | Run only flows whose names match the pattern | | `--device ` | Run on one specific local device | | `--devices ,` | Run on specific devices in parallel mode | ### Parallelism and execution control | Flag | Description | | --------------------------- | -------------------------------------------------- | | `--parallel` | Auto-discover devices and run flows in parallel | | `--workers ` | Max workers per platform in parallel mode | | `--retries ` | Retry failed flows `n` times | | `--bail ` | Stop scheduling new flows after `n` final failures | | `--shard /` | Run one deterministic CI shard | | `--debug-on-failure` | Open an interactive REPL on the first failure | ### Iteration helpers | Flag | Description | | -------------------- | -------------------------------------------------- | | `--watch` | Re-run when flows or config change | | `--changed` | Run only changed flow files from git | | `--last-failed` | Re-run only flows that failed in the last run | | `--update-baselines` | Rewrite screenshot baselines for visual regression | ### Output and configuration | Flag | Description | | ------------------- | ------------------------------------------------------------------------------- | | `--reporter ` | Reporter: `console`, `json`, `junit`, `html`, `allure`, or a custom module path | | `--config ` | Use a non-default config file | | `--validate-config` | Validate config and exit before discovery | | `--quiet`, `-q` | Suppress pass output and show failures plus summary | | `--verbose` | Print detailed failure diagnostics and hierarchy | | `--json` | Emit machine-readable output where supported | ### Appium and cloud overrides | Flag | Description | | -------------------------- | ----------------------------------------------------- | | `--driver ` | Override `execution.mode` | | `--appium-url ` | Override `execution.appium.serverUrl` | | `--caps ` | Load Appium capabilities from JSON | | `--caps-json ` | Inline Appium capabilities JSON | | `--no-provider-reporting` | Skip BrowserStack/Sauce Labs session result reporting | ### Examples ```bash # Run the whole suite spana test # Run one file on web spana test flows/login.flow.ts --platform web # Run smoke flows on Android and iOS spana test --tag smoke --platform android,ios # Run the last failures only spana test --last-failed # Re-run automatically while editing flows spana test --watch # Parallelize across discovered devices spana test --parallel --workers 2 # Pin the run to specific devices spana test --platform android,ios --devices emulator-5554,SIM-1 # Refresh screenshot baselines spana test --update-baselines ``` ### Framework-app multi-device showcase When you want a concrete local showcase run from this repo, start in `packages/spana` so the bundled framework demo config and flows resolve directly: ```bash # Inspect the device IDs you can target spana devices # Iterate on one pinned device first spana test ./flows/framework-app --config ./spana.config.ts --platform android --device emulator-5554 # Then fan out the same showcase flows across specific Android + iOS targets spana test ./flows/framework-app \ --config ./spana.config.ts \ --platform android,ios \ --devices emulator-5554, \ --parallel \ --workers 1 ``` Use `--device` when you want one reproducible local target while debugging a flow, then switch to `--devices` plus `--parallel` when you want the framework-app demo to showcase the same suite across multiple local devices. CLI flags override `spana.config.ts`. Filtering happens before sharding, so each shard sees a deterministic slice of the already-filtered flow list. ## `spana hierarchy` Dump the current UI hierarchy from a live session. ```bash spana hierarchy --platform [--config path] [--json] [--pretty] ``` Use this to inspect the raw element tree when selectors are not behaving as expected. ## `spana selectors` List actionable elements and suggested selectors for the current screen. ```bash spana selectors --platform [--config path] [--json] [--pretty] ``` This command connects to the running app, inspects the hierarchy, and returns the best selectors Spana can infer for each visible element. For deeper examples of both commands, see [Agent Commands](/cli/agent-commands/). ## `spana validate` Validate flow files without connecting to devices. ```bash spana validate [path] [--json] ``` `path` defaults to `./flows`. Validation checks that flows load correctly and that project-level flow issues are surfaced before a real run. ## `spana validate-config` Validate `spana.config.ts` without starting drivers or discovering flows. ```bash spana validate-config [path] [--config path] [--json] ``` This is useful in CI or pre-commit hooks when you want a fast config sanity check. ## `spana doctor` Check environment readiness before running tests. ```bash spana doctor [options] ``` | Flag | Description | | ------------------------------ | --------------------------------------- | | `--platform ` | Limit diagnostics to selected platforms | | `--config ` | Load a specific config file | | `--driver ` | Force local or Appium diagnostics | | `--appium-url ` | Override the Appium endpoint under test | | `--caps ` | Load Appium capabilities from a file | | `--caps-json ` | Inline Appium capabilities JSON | | `--json` | Emit machine-readable doctor results | | `--pretty` | Pretty-print JSON output | Use `doctor` before a new CI environment, after simulator/device setup changes, or when a session fails to start and you want a quick readiness report. ## `spana studio` Launch the Studio UI for recording, inspection, and running flows. ```bash spana studio [--config path] [--port 4400] [--no-open] ``` See [Studio](/cli/studio/) for the full workflow. ## `spana init` Scaffold a new Spana project. ```bash spana init [--preset ] [--force] ``` See [Init](/cli/init/) for the generated config and starter flow. ## `spana init-flow` Generate a starter `.flow.ts` file. ```bash spana init-flow [options] ``` | Flag | Description | | ------------------------------ | --------------------------------------- | ------ | ----------------------------------- | | `--platform ` | Add platform tags to the generated flow | | `--tag ` | Add custom tags | | `--preset ` | Start from a built-in flow template | | `--output ` | Write to a custom file path | | `--force` | Overwrite an existing file | ### Examples ```bash spana init-flow "checkout smoke" --preset smoke --platform web,android --tag smoke spana init-flow "login auth" --preset auth --output flows/auth/login.flow.ts ``` ## `spana devices` List connected devices and simulators. ```bash spana devices [--json] ``` Output includes platform, device name, device type, and connection state. This is the fastest way to confirm the IDs you should pass to `--device` or `--devices`. ## `spana version` Print the installed CLI version. ```bash spana version ``` ## Exit codes | Code | Meaning | | ---- | ----------------- | | `0` | Command succeeded | | `1` | Command failed | --- ## Agent Commands spana includes three commands designed specifically for AI agent-driven test authoring. They allow an agent to inspect the current UI state, generate flows, and validate them without needing a device connection. ## `spana selectors` List all actionable elements on screen with suggested selectors. ```bash spana selectors --platform [--config path] [--json] [--pretty] ``` Plain output is a JSON array. With `--json`, Spana wraps that array in a versioned machine-readable envelope. ```bash spana selectors --platform android ``` ```json [ { "testID": "login-button", "text": "Sign In", "accessibilityLabel": null, "bounds": { "x": 24, "y": 480, "width": 328, "height": 48 }, "suggestedSelector": { "testID": "login-button" } }, { "testID": null, "text": "Forgot password?", "accessibilityLabel": null, "bounds": { "x": 120, "y": 544, "width": 136, "height": 20 }, "suggestedSelector": { "text": "Forgot password?" } } ] ``` `suggestedSelector` follows priority: `testID` > `accessibilityLabel` > `text`. Feed this output directly to an agent to choose which element to interact with. ### Filtering with `jq` ```bash # Elements that have a testID spana selectors --platform web | jq '.[] | select(.testID != null)' # Just the suggested selectors spana selectors --platform ios | jq '[.[].suggestedSelector]' ``` ## `spana hierarchy` Dump the full UI element tree as structured JSON. ```bash spana hierarchy --platform [--config path] [--json] [--pretty] ``` Plain output is the raw hierarchy JSON. With `--json`, Spana wraps it in a versioned machine-readable envelope. ```bash spana hierarchy --platform web --pretty ``` ```json { "role": "application", "children": [ { "role": "main", "children": [ { "role": "textbox", "testID": "email-input", "text": "", "bounds": { "x": 24, "y": 200, "width": 328, "height": 44 } } ] } ] } ``` Use `spana hierarchy` when `spana selectors` does not include the element you need, or to understand the structural relationship between elements. ## `spana validate` Validate flow files without a device connection. Catches common mistakes before running tests. ```bash spana validate [path] [--json] ``` `path` defaults to `flowDir`. Exits `0` if all flows are valid, non-zero if any errors found. Does not execute the flows. **Checks performed:** - Flow files have a valid default export with `name` and `fn` - No duplicate flow names across files - Platform values are valid (`web`, `android`, `ios` only) - Flow directory exists and contains flow files ```bash spana validate # ✓ 5 flow(s) valid spana validate flows/ # ✗ flows/login.flow.ts: Duplicate flow name "Login test" (also in flows/auth.flow.ts) # ✗ flows/broken.flow.ts: Invalid platform "windows" — must be web, android, or ios # ✗ flows/empty.flow.ts: export default is not a FlowDefinition ``` Use `spana validate` in CI preflight or as part of an agent loop before committing generated flow files. ## Agent workflow The typical agent-driven authoring loop: ```bash # 1. Navigate the app to the screen you want to test, then discover elements spana selectors --platform android | jq '.[] | select(.testID != null)' # 2. Generate and write a flow file (done by the agent) # 3. Validate the flow without a device spana validate flows/my-new-flow.ts # 4. Run the flow and capture JSON results spana test flows/my-new-flow.ts --reporter json 2>&1 # 5. Read errors from JSON output and iterate spana test flows/my-new-flow.ts --reporter json 2>&1 | jq '.results[] | select(.status == "failed")' ``` This loop requires no manual interaction. `spana validate` catches structural errors before device time is spent. `--reporter json` gives the agent machine-readable pass/fail data with error messages. ```mermaid graph LR A[Agent] -->|spana selectors| B[Discover elements] B -->|generate code| C[Write flow.ts] C -->|spana validate| D[Validate schema] D -->|spana test --reporter json| E[Execute on device] E -->|read JSON errors| F[Fix and retry] F --> C ``` ## Agent skill file spana ships with a ready-made skill file for AI coding agents at `.agents/skills/spana-testing/SKILL.md` in the repo. It covers element discovery, flow writing patterns, selectors, validation, error handling, and platform-specific notes. **To use it with your AI agent:** 1. Copy the skill file into your project: ```bash mkdir -p .agents/skills/spana-testing cp node_modules/spana-test/.agents/skills/spana-testing/SKILL.md .agents/skills/spana-testing/ ``` 2. Or reference it in your `CLAUDE.md` / `AGENTS.md`: ```markdown ## Testing For writing E2E tests, follow the spana testing skill at: .agents/skills/spana-testing/SKILL.md ``` 3. Or point your agent to it directly: ``` Read .agents/skills/spana-testing/SKILL.md and use it to write a test for the login flow. ``` The skill file is self-contained — it includes the full API reference, workflow loop, and common patterns so the agent can start writing tests immediately. --- ## Init The `spana init` command generates a starter config file and example flow through an interactive wizard. ## Usage ```bash spana init ``` ### Options | Flag | Description | | --------- | ----------------------------------------------- | | `--force` | Overwrite existing `spana.config.ts` if present | ## What it does The wizard asks: 1. **Which platforms to test** -- web (Playwright), Android (UiAutomator2), iOS (WebDriverAgent) 2. **App details** per platform: - Web: app URL (default `http://localhost:3000`) - Android: package name (default `com.example.myapp`) - iOS: bundle ID (default `com.example.myapp`) Then it creates: | File | Description | | ----------------------- | ------------------------------------------------ | | `spana.config.ts` | Config file with your platform and app settings | | `flows/example.flow.ts` | Starter flow with a smoke test you can customize | ## Generated config ```ts title="spana.config.ts" import { defineConfig } from "spana-test"; export default defineConfig({ apps: { web: { url: "http://localhost:3000" }, android: { packageName: "com.example.myapp" }, }, platforms: ["web", "android"], flowDir: "./flows", reporters: ["console"], defaults: { waitTimeout: 5_000, }, }); ``` ## Generated flow ```ts title="flows/example.flow.ts" import { flow } from "spana-test"; export default flow( "Example - app loads successfully", { tags: ["smoke"], platforms: ["web", "android"] }, async ({ app, expect }) => { await expect({ text: "Hello" }).toBeVisible(); }, ); ``` ## Next steps After running `spana init`: 1. Install spana: `npm install -D spana-test` 2. Add `spana-output` to your `.gitignore` 3. Edit `flows/example.flow.ts` with selectors from your app 4. Discover selectors: `spana selectors` 5. Run tests: `spana test` --- ## Studio Spana Studio is a local web interface that bundles an **Element Inspector** and a **Test Runner Dashboard** into a single tool. It lets you visually inspect device screens, explore element trees, and run test flows with real-time feedback — all from your browser. ## Launching Studio ```bash spana studio [options] ``` ### Options | Flag | Description | | ----------------- | -------------------------------------------------- | | `--port ` | Port to serve on (default: `4400`) | | `--no-open` | Don't auto-open the browser | | `--config ` | Path to config file (default: `./spana.config.ts`) | ```bash # Start on the default port and open the browser spana studio # Use a custom port, skip auto-open spana studio --port 4000 --no-open # Point at a non-default config spana studio --config ./config/spana.staging.ts ``` ## Element Inspector ![Studio Inspector](../../../assets/studio-inspector.png) Connect to a running device or simulator, then interact with a live screenshot of the current screen. - **Tap to inspect** — click any element in the screenshot to see its properties (testID, text, accessibility label, bounds). - **Element tree** — browse the full hierarchy in a sidebar tree view. - **Copy selectors** — one-click copy of the best selector for any element, ready to paste into a flow file. This gives you the same information as `spana selectors` and `spana hierarchy`, but in a visual, point-and-click workflow. ## Test Runner Dashboard ![Studio Test Runner](../../../assets/studio-runner.png) Discover and run flow files without leaving the browser. - **Flow discovery** — automatically lists all flows found under your configured `flowDir`. - **Device selector** — pick the target device, emulator, or simulator for each selected platform from the toolbar. - **Run tests** — execute one or many flows with real-time progress updates. - **Step details** — expand any step to see its status, duration, and captured screenshot. ### Capture toggles Two checkboxes control screenshot capture during a run: | Toggle | Behavior | | ----------------- | ---------------------------------------------------------- | | **Screenshots** | Capture a screenshot on each successful step | | **Step captures** | Capture per-step screenshots (useful for visual debugging) | ### Session persistence Test results persist across tab switches within the same Studio session. You can jump between the Inspector and the Runner without losing run history or step details. ## How it works Studio is an embedded React frontend served directly from the CLI binary — no separate install required. The frontend communicates with the CLI backend through an oRPC API layer, giving you type-safe requests between the browser and device connections. ## Development If you're working on Studio itself, run the Vite dev server with hot reload: ```bash cd apps/studio bun run dev ``` The dev frontend connects directly to the CLI backend at `http://localhost:4400`. --- ## Reporters Spana ships five reporters. Use one or combine several to get both human-readable output and machine-readable artifacts from the same run. ## Enabling reporters **CLI flag** (one or more): ```bash spana test --reporter console --reporter html ``` **Config file** (`spana.config.ts`): ```ts export default defineConfig({ reporters: ["console", "html"], }); ``` Multiple reporters run simultaneously. Each receives the same flow results as they complete. --- ## Console (default) Human-readable terminal output with pass/fail symbols, per-platform summaries, and failure details. **Enable:** active by default. Explicitly: `--reporter console`. **Output:** stdout. ``` ✓ [web] login flow (1243ms) ✗ [android] login flow (3891ms) web (Playwright) ✓ 1/1 passed (1.2s) android (UiAutomator2) ✗ 0/1 passed (3.9s) --- Failures --- ✗ [android] login flow Timed out waiting for selector "welcome-text" 1/2 passed, 1 failed (3.9s) ``` Flaky tests (passed on retry) are marked with `~` and show the attempt number. Scenario steps (Given/When/Then) are printed inline when using Gherkin-style flows. **When to use:** local development and quick CI feedback. --- ## JSON Streams newline-delimited JSON events to stdout. Each line is a self-contained JSON object. **Enable:** `--reporter json` **Output:** stdout (one JSON object per line). Events emitted: | Event | When | | ------------- | ---------------------------------------------- | | `flowPass` | A flow finishes successfully | | `flowFail` | A flow fails | | `runComplete` | All flows have finished; includes full summary | ```json {"event":"flowPass","name":"login flow","platform":"web","status":"passed","durationMs":1243} {"event":"flowFail","name":"login flow","platform":"android","status":"failed","durationMs":3891,"error":{"message":"Timed out"}} {"event":"runComplete","total":2,"passed":1,"failed":1,"skipped":0,"flaky":0,"durationMs":3891} ``` **When to use:** piping results into other tools, custom dashboards, or CI scripts that parse structured output. --- ## JUnit Generates a JUnit XML file compatible with Jenkins, GitHub Actions, GitLab CI, and most CI systems that consume test reports. **Enable:** `--reporter junit` **Output:** `/junit-report.xml` (default `./spana-output/junit-report.xml`). ```xml ... ``` Results are grouped by platform into `` elements. Scenario steps, driver steps, and attachments are included in `` when present. **When to use:** CI pipelines that display JUnit test results (GitHub Actions `test-reporter`, Jenkins JUnit plugin, GitLab test reports). --- ## HTML ![HTML Report](../../../assets/html-report.png) Self-contained HTML report with a dark theme, responsive layout, and embedded screenshots (base64-inlined so no external files are needed). **Enable:** `--reporter html` **Output:** `/report.html` (default `./spana-output/report.html`). The report includes: - **Summary cards** -- passed/total, total time, platform count. - **Per-platform sections** -- status badge, duration, driver and scenario steps. - **Step screenshots** -- inline images from each step that captured a screenshot. - **Final-state screenshots** -- side-by-side comparison of the final screen on each platform. - **Failure details** -- error messages displayed inline. **When to use:** sharing results with teammates, reviewing visual state after a run, or archiving test evidence. --- ## Allure Generates [Allure](https://allurereport.org/) result files for rich CI dashboards with history, trends, and categorized failures. **Enable:** `--reporter allure` **Output:** `allure-results/` directory (default), containing `*-result.json` files and an `environment.properties` file. ```bash # Run tests with Allure reporter spana test --reporter console,allure # Generate and open the Allure report npx allure generate allure-results --clean -o allure-report npx allure open allure-report ``` The reporter produces: - **Result files** — one JSON file per flow with UUID, history ID, labels, steps, and timing - **Attachments** — screenshots and hierarchy dumps copied into the output directory - **Environment properties** — platform, framework name, pass/fail counts - **Flaky detection** — tests that pass on retry are tagged as `flaky` with attempt count - **Step mapping** — spana steps (tap, assertVisible, etc.) map to Allure test steps with status and duration **When to use:** CI dashboards that support Allure (Jenkins Allure Plugin, GitHub Actions with `allure-report` action, GitLab with Allure integration). --- ## Combining reporters A common setup for CI: ```ts export default defineConfig({ reporters: ["console", "junit", "html"], }); ``` This gives you live terminal feedback, a JUnit file for CI test-result ingestion, and an HTML report to upload as a build artifact. --- ## Custom reporters Need a reporter that isn't built in? See [Custom Reporters](/reference/custom-reporters/) to learn how to write your own using spana's `Reporter` interface. --- ## Custom Reporters Custom reporters let you push results into Slack, internal dashboards, CSV files, metrics systems, or any other destination. ## Reporter shape Import reporter types from `spana-test`: ```ts import type { Reporter, FlowResult, RunSummary } from "spana-test"; const reporter: Reporter = { onFlowStart(name, platform, workerName) { console.log(`START ${platform}:${workerName ?? "default"} ${name}`); }, onFlowFail(result: FlowResult) { console.log(`FAIL ${result.name}: ${result.error?.message}`); }, onRunComplete(summary: RunSummary) { console.log(`${summary.passed}/${summary.total} passed`); }, }; export default reporter; ``` All hooks except `onRunComplete` are optional. ## Registering a reporter ```ts import { defineConfig } from "spana-test"; export default defineConfig({ reporters: ["console", "./reporters/slack.ts"], }); ``` Reporter module paths are resolved relative to `spana.config.ts`. ## Factory reporters If your reporter needs options, export a factory function: ```ts import type { Reporter } from "spana-test"; export default function createCsvReporter(options: { outputDir: string }): Reporter { return { onRunComplete(summary) { console.log(`Write results into ${options.outputDir}`); }, }; } ``` Spana calls factory reporters with `{ outputDir }`. ## Exported types ### `Reporter` ```ts interface Reporter { onFlowStart?(name: string, platform: Platform, workerName?: string): void; onFlowPass?(result: FlowResult): void; onFlowFail?(result: FlowResult): void; onRunComplete(summary: RunSummary): void; flowCount?: number; platformFlowCounts?: Partial>; } ``` `flowCount` and `platformFlowCounts` are populated by Spana so console-style reporters can render progress. ### `FlowResult` | Field | Description | | --------------- | ----------------------------------------------------------- | | `name` | Flow name | | `platform` | `web`, `android`, or `ios` | | `status` | `passed`, `failed`, or `skipped` | | `flaky` | `true` when the flow failed first and later passed on retry | | `attempts` | Number of attempts made | | `durationMs` | Total runtime in milliseconds | | `error` | Structured `FlowError` for failed flows | | `attachments` | Captured artifacts such as screenshots, HAR, or logs | | `steps` | Low-level driver steps recorded for the flow | | `scenarioSteps` | Gherkin step results for scenario-style flows | | `workerName` | Worker or device name when parallel mode is enabled | ### `RunSummary` | Field | Description | | ------------------------------- | -------------------------------------------------- | | `total` | Total flow executions across all platforms | | `passed` / `failed` / `skipped` | Final result counts | | `flaky` | Number of flaky flows | | `durationMs` | Total run duration | | `results` | All `FlowResult` entries | | `platforms` | Platforms included in the run | | `bailedOut` | `true` when `--bail` stopped the run early | | `bailLimit` | Bail threshold that triggered the stop | | `workerStats` | Per-worker timing and flow counts in parallel mode | ### `StepResult` and `ScenarioStepResult` `StepResult` represents low-level driver actions such as taps, assertions, typing, or network setup. `ScenarioStepResult` represents higher-level Gherkin steps such as `Given`, `When`, `Then`, `And`, `Before`, and `After`. Each scenario step can include nested `steps` for the underlying driver actions. ### `Attachment` ```ts interface Attachment { name: string; contentType: string; path: string; } ``` Attachments point at files on disk, for example screenshots, hierarchy dumps, console logs, JavaScript errors, or HAR captures. ### `FlowError` and `FailureCategory` ```ts interface FlowError { message: string; stack?: string; category: FailureCategory; suggestion?: string; errorCode?: string; } ``` `FailureCategory` values include: - `element-not-found` - `element-not-visible` - `element-off-screen` - `element-not-interactive` - `text-mismatch` - `timeout` - `device-disconnected` - `app-crashed` - `app-not-installed` - `driver-error` - `config-error` - `unknown` ## Example: failure webhook ```ts import type { Reporter } from "spana-test"; const reporter: Reporter = { async onFlowFail(result) { await fetch("https://hooks.example.com/test-failures", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: result.name, platform: result.platform, category: result.error?.category, message: result.error?.message, worker: result.workerName, attachments: result.attachments?.map((attachment) => attachment.name), }), }); }, onRunComplete(summary) { console.log(`${summary.failed} failed flow(s)`); }, }; export default reporter; ``` --- ## Agent API The `spana-test/agent` export gives you a persistent automation session outside the flow runner. It is useful for custom scripts, AI agents, internal tooling, and live debugging. ## Installation The agent API ships with `spana-test`. ```ts import { connect, validateFlows } from "spana-test/agent"; ``` ## Connecting ```ts import { connect } from "spana-test/agent"; const session = await connect({ platform: "web", baseUrl: "http://localhost:3000", headless: false, }); await session.tap({ testID: "login-button" }); await session.disconnect(); ``` ## `ConnectOptions` ```ts interface ConnectOptions { platform: "web" | "android" | "ios"; device?: string; baseUrl?: string; browser?: "chromium" | "firefox" | "webkit"; headless?: boolean; storageState?: string; verboseLogging?: boolean; storybook?: { url?: string; iframePath?: string; }; packageName?: string; bundleId?: string; } ``` | Option | Platform | Description | | ---------------- | ------------ | -------------------------------------------------- | | `platform` | all | Target platform | | `device` | android, ios | Explicit device ID from `spana devices` | | `baseUrl` | web | Base URL to open when the browser session starts | | `browser` | web | Browser engine: `chromium`, `firefox`, or `webkit` | | `headless` | web | Run the browser headless, default `true` | | `storageState` | web | Preload Playwright cookies and storage state | | `verboseLogging` | web | Print verbose Playwright runtime logs | | `storybook` | web | Storybook URL and iframe config for `openStory()` | | `packageName` | android | Android application ID | | `bundleId` | ios | iOS bundle identifier | ## Session methods ### Touch and input | Method | Signature | Description | | ----------------- | ------------------------------------ | -------------------------------------------------- | | `tap` | `(selector) => Promise` | Tap an element | | `tapXY` | `(x, y) => Promise` | Tap at absolute coordinates | | `doubleTap` | `(selector, opts?) => Promise` | Double-tap an element | | `longPress` | `(selector, opts?) => Promise` | Long-press an element | | `longPressXY` | `(x, y, opts?) => Promise` | Long-press at coordinates | | `inputText` | `(text) => Promise` | Type into the focused control | | `pressKey` | `(key) => Promise` | Send a named key | | `hideKeyboard` | `() => Promise` | Dismiss the software keyboard | | `dismissKeyboard` | `(opts?) => Promise` | Use the platform-aware keyboard dismissal strategy | ### Navigation and gestures | Method | Signature | Description | | -------------------- | ----------------------------------------------------- | ----------------------------------------- | | `swipe` | `(direction, opts?) => Promise` | Swipe up, down, left, or right | | `scroll` | `(direction) => Promise` | Scroll in one direction | | `scrollUntilVisible` | `(selector, opts?) => Promise` | Scroll until a target appears | | `backUntilVisible` | `(selector, opts?) => Promise` | Repeatedly go back until a target appears | | `pinch` | `(selector, { scale?, duration? }?) => Promise` | Pinch on a mobile element | | `zoom` | `(selector, { scale?, duration? }?) => Promise` | Zoom on a mobile element | | `multiTouch` | `(sequences) => Promise` | Run multiple touch sequences at once | ### App lifecycle | Method | Signature | Description | | ------------ | -------------------------------------- | --------------------------------------------- | | `launch` | `(opts?) => Promise` | Launch the app or page | | `stop` | `() => Promise` | Stop the app | | `kill` | `() => Promise` | Force-kill the app | | `clearState` | `() => Promise` | Clear app/browser state | | `openLink` | `(url) => Promise` | Open a URL or deep link | | `openStory` | `(storyId, options?) => Promise` | Open a Storybook story in the browser runtime | | `back` | `() => Promise` | Trigger browser back or Android back | `openStory()` is web-only and uses the `storybook` connection settings when provided. ### Queries and inspection | Method | Signature | Description | | -------------- | ---------------------------------------------------- | -------------------------------------------- | | `hierarchy` | `() => Promise` | Read the full current hierarchy | | `selectors` | `() => Promise` | Get suggested selectors for visible elements | | `screenshot` | `() => Promise` | Capture a screenshot | | `getText` | `(selector, opts?) => Promise` | Read an element's text | | `getAttribute` | `(selector, name, opts?) => Promise` | Read an attribute | | `isVisible` | `(selector, opts?) => Promise` | Check visibility without throwing | | `isEnabled` | `(selector, opts?) => Promise` | Check enabled state without throwing | | `evaluate` | `(fn \| string, ...args) => Promise` | Run JavaScript in the web page | ### Browser helpers | Method | Signature | Description | | ---------------------- | -------------------------------------------------- | ------------------------------------------------- | | `mockNetwork` | `(matcher, response) => Promise` | Fulfill matching requests with mocked data | | `blockNetwork` | `(matcher) => Promise` | Abort matching requests | | `clearNetworkMocks` | `() => Promise` | Remove active network mocks | | `setNetworkConditions` | `(conditions) => Promise` | Simulate network conditions — profiles, custom throttling, or offline mode | | `saveCookies` | `(path) => Promise` | Persist cookies to disk | | `loadCookies` | `(path) => Promise` | Load cookies from disk | | `saveAuthState` | `(path) => Promise` | Save Playwright storage state | | `loadAuthState` | `(path) => Promise` | Replace the browser context with saved auth state | | `downloadFile` | `(path) => Promise` | Save the next browser download | | `uploadFile` | `(selector, path) => Promise` | Upload a local file through a file input | | `newTab` | `(url?) => Promise` | Open a new browser tab | | `switchToTab` | `(index) => Promise` | Switch to a tab by index | | `closeTab` | `() => Promise` | Close the current tab | | `getTabIds` | `() => Promise` | List known tab IDs | | `getConsoleLogs` | `() => Promise>` | Read captured console messages | | `getJSErrors` | `() => Promise>` | Read uncaught JavaScript errors | | `getHAR` | `() => Promise>` | Read the current HAR network capture | These helpers are available on local Playwright web sessions. #### `setNetworkConditions()` Simulate degraded or offline network conditions across all platforms. You can use a named profile or supply custom values. **Available profiles:** `wifi`, `4g`, `3g`, `2g`, `edge`, `offline` ```ts // Simulate 3G network await session.setNetworkConditions({ profile: "3g" }); // Go offline await session.setNetworkConditions({ profile: "offline" }); // Back to normal await session.setNetworkConditions({ profile: "wifi" }); // Custom values await session.setNetworkConditions({ latencyMs: 150, downloadThroughputKbps: 1000, uploadThroughputKbps: 500, }); ``` **Platform support:** | Platform | Offline | Profiles | Custom Values | |---|---|---|---| | Web (Chromium) | Yes | Yes | Yes | | Web (Firefox/WebKit) | Yes | No | No | | Android emulator | Yes | Yes | Yes | | Android device | Yes | No | No | | iOS simulator | Yes | Yes (sudo) | Yes (sudo) | | Appium cloud | Yes | Yes | varies | ### Hybrid / WebView helpers | Method | Signature | Description | | ------------------- | ------------------------------ | ------------------------------------- | | `getContexts` | `() => Promise` | List native and WebView contexts | | `getCurrentContext` | `() => Promise` | Read the active context ID | | `switchToContext` | `(contextId) => Promise` | Switch to a specific context | | `switchToWebView` | `() => Promise` | Switch to the first available WebView | | `switchToNativeApp` | `() => Promise` | Switch back to the native context | ### Cleanup | Method | Signature | Description | | ------------ | --------------------- | -------------------------------------------------- | | `disconnect` | `() => Promise` | Release the session and clean up runtime resources | ## `validateFlows(path)` The same package also exports programmatic validation: ```ts import { validateFlows } from "spana-test/agent"; const issues = await validateFlows("./flows"); if (issues.length > 0) { console.error(issues); } ``` ## Examples ### Web + Storybook ```ts const session = await connect({ platform: "web", baseUrl: "http://localhost:3000", storybook: { url: "http://localhost:6006" }, storageState: "./auth/admin.json", }); await session.openStory("components-button--primary", { globals: { theme: "dark" }, }); await session.getConsoleLogs(); await session.disconnect(); ``` ### Android ```ts const session = await connect({ platform: "android", packageName: "com.example.app", device: "emulator-5554", }); await session.tap({ testID: "login-button" }); await session.disconnect(); ``` ### iOS ```ts const session = await connect({ platform: "ios", bundleId: "com.example.app", device: "00008110-001C195E0E12801E", }); await session.switchToWebView(); await session.disconnect(); ``` --- ## API Reference ## app methods All methods return `Promise` unless noted. ### Interaction | Method | Signature | Description | |---|---|---| | `tap` | `(selector, opts?)` | Tap an element matching the selector | | `tapXY` | `(x, y)` | Tap at absolute screen coordinates | | `doubleTap` | `(selector, opts?)` | Double-tap an element | | `longPress` | `(selector, opts?)` | Long-press an element | | `longPressXY` | `(x, y, opts?)` | Long-press at coordinates | | `inputText` | `(text)` | Type text into the focused element | | `pressKey` | `(key)` | Press a named key | | `hideKeyboard` | `()` | Dismiss the software keyboard | | `swipe` | `(direction, opts?)` | Swipe in a direction | | `scroll` | `(direction)` | Scroll in a direction | Direction: `"up" | "down" | "left" | "right"` ### App lifecycle | Method | Signature | Description | |---|---|---| | `launch` | `(opts?)` | Launch the app | | `stop` | `()` | Stop the app | | `kill` | `()` | Force-kill the app | | `clearState` | `()` | Clear app data/state | | `openLink` | `(url)` | Open a URL or deep link | | `back` | `()` | Press the back button (Android) | ### Utilities | Method | Signature | Description | |---|---|---| | `takeScreenshot` | `()` | `Promise` — capture the current screen | ## expect methods ```ts expect(selector: Selector): PromiseExpectation ``` | Method | Signature | Description | |---|---|---| | `toBeVisible` | `(opts?)` | Assert element is present and visible | | `toBeHidden` | `(opts?)` | Assert element is absent or not visible | | `toHaveText` | `(expected, opts?)` | Assert element text contains `expected` | ## Selectors | Type | Example | Notes | |---|---|---| | `string` | `"login-btn"` | Shorthand for `{ testID: "login-btn" }` | | `testID` | `{ testID: "login-btn" }` | `data-testid` / `accessibilityIdentifier` / `resource-id` | | `text` | `{ text: "Sign In" }` | Visible label, partial match | | `accessibilityLabel` | `{ accessibilityLabel: "Close" }` | OS accessibility label | | `point` | `{ point: { x: 100, y: 200 } }` | Absolute coordinates, last resort | ## WaitOptions Accepted by all selector-based `app` methods and all `expect` methods. ```ts interface WaitOptions { timeout?: number; // ms pollInterval?: number; // ms settleTimeout?: number; // ms } ``` ## FlowConfig ```ts interface FlowConfig { tags?: string[]; platforms?: Array<"web" | "android" | "ios">; timeout?: number; autoLaunch?: boolean; launchOptions?: LaunchOptions; } interface LaunchOptions { clearState?: boolean; clearKeychain?: boolean; deepLink?: string; launchArguments?: Record; deviceState?: { language?: string; locale?: string; timeZone?: string; }; } ``` ## defineConfig options ```ts interface SpanaConfig { apps?: { web?: { url: string }; android?: { packageName: string }; ios?: { bundleId: string }; }; platforms?: Array<"web" | "android" | "ios">; flowDir?: string; launchOptions?: LaunchOptions; reporters?: string[]; defaults?: { waitTimeout?: number; pollInterval?: number; settleTimeout?: number; retries?: number; }; artifacts?: { outputDir?: string; captureOnFailure?: boolean; captureOnSuccess?: boolean; screenshot?: boolean; uiHierarchy?: boolean; }; hooks?: { beforeAll?: (ctx: HookContext) => Promise; beforeEach?: (ctx: HookContext) => Promise; afterEach?: (ctx: HookContext) => Promise; afterAll?: (ctx: HookContext) => Promise; }; } ``` ## CLI flags | Command | Key flags | |---|---| | `spana test [path]` | `--platform`, `--tag`, `--grep`, `--reporter`, `--config` | | `spana hierarchy` | `--platform`, `--pretty` | | `spana selectors` | `--platform`, `--pretty` | | `spana validate [path]` | — | | `spana devices` | — | | `spana version` | — | --- ## Architecture Overview spana uses a layered architecture where all logic lives in TypeScript on the host machine. Platform drivers are thin HTTP clients with no embedded intelligence. ## High-level architecture ```mermaid graph TD A[flow files .flow.ts] --> B[CLI: spana test] B --> C[TestRunner / runner.ts] C --> D[PlatformOrchestrator] D -->|parallel platforms| E1[Web: Playwright CDP] D -->|parallel platforms| E2[Android: UiAutomator2] D -->|parallel platforms| E3[iOS: WebDriverAgent] E1 --> F[Reporter] E2 --> F E3 --> F F --> G1[console] F --> G2[json] F --> G3[junit] F --> G4[html] ``` Platforms run in parallel. Within each platform, flows run serially. Results are collected and passed to the configured reporter(s). ## Layered architecture ```mermaid graph TD subgraph User API A1["flow() — define test"] A2["app — launch, tap, swipe, type"] A3["expect — toBeVisible, toHaveText, toBeHidden"] end subgraph Smart Layer [Smart Layer — src/smart/] B1[coordinator.ts — action dispatch] B2[auto-wait.ts — poll until element appears] B3[element-matcher.ts — client-side tree search + centerOf] end subgraph Raw Driver [Raw Driver — src/drivers/raw-driver.ts] C[RawDriverService interface] C1[tapAtCoordinate / swipe / inputText] C2[dumpHierarchy — returns raw XML or JSON] C3[launchApp / stopApp / takeScreenshot] end subgraph Companion Drivers D1[playwright.ts — CDP via Playwright] D2[uiautomator2/driver.ts — HTTP to APK server] D3[wda/driver.ts — HTTP to XCTest runner] end subgraph Devices E1[Browser / Chromium] E2[Android emulator or device] E3[iOS simulator or device] end A2 --> B1 A3 --> B1 B1 --> B2 B2 --> C2 B2 --> B3 B3 --> B1 B1 --> C1 C --> D1 C --> D2 C --> D3 D1 --> E1 D2 --> E2 D3 --> E3 ``` The Smart Layer never sees raw coordinates. It resolves selectors to elements, derives center coordinates, then calls the thin `RawDriver` interface. The `RawDriver` knows nothing about selectors. ## Element resolution flow How `app.tap({ testID: "login" })` executes end-to-end: ```mermaid sequenceDiagram participant Flow as flow.ts participant Coord as coordinator.ts participant Wait as auto-wait.ts participant Driver as RawDriverService participant Parser as platform parser participant Companion as companion server Flow->>Coord: tap({ testID: "login" }) Coord->>Wait: waitForElement(selector) loop poll until found or timeout Wait->>Driver: dumpHierarchy() Driver->>Companion: HTTP GET /source Companion-->>Driver: raw XML / JSON string Driver-->>Wait: RawHierarchy Wait->>Parser: parse(raw) -> Element tree Wait->>Wait: findElement(tree, { testID: "login" }) end Wait-->>Coord: Element (with bounds) Coord->>Coord: centerOf(element) -> {x, y} Coord->>Driver: tapAtCoordinate(x, y) Driver->>Companion: HTTP POST /touch/perform ``` The parser is platform-specific (XML for Android/iOS, JSON for web) but always produces the same unified `Element` tree shape. All matching logic runs client-side in TypeScript. ## Parallel execution ```mermaid graph TD subgraph Flow Queue [Shared flow queue] Q1[flow 1] Q2[flow 2] Q3[flow 3] Q4[flow 4] Q5[flow 5] end subgraph Workers W1[Worker A — Pixel 7] W2[Worker B — Galaxy S23] W3[Worker C — iPhone 15 sim] end Q1 --> W1 Q2 --> W2 Q3 --> W3 Q4 --> W1 Q5 --> W2 W1 --> R[Aggregated Results] W2 --> R W3 --> R ``` Workers share a single atomic index into the flow array. Because Bun is single-threaded, the increment is naturally safe with no mutex. A faster device finishes sooner and picks up the next flow immediately, draining the queue at the speed of the fastest workers. - `parallel.ts` — `runParallel()` launches all workers with `Promise.all`, each looping over the queue until exhausted. - `orchestrator.ts` — `orchestrate()` runs one worker per platform with all flows for that platform in series, platforms in parallel. ## Agent workflow ```mermaid graph LR A[Agent] -->|spana selectors --platform android| B[Discover elements\nJSON list with suggestedSelector] B -->|generate flow code| C[Write flow.ts] C -->|spana validate| D[Validate schema\nno device needed] D -->|spana test --reporter json| E[Execute on device] E -->|read JSON errors| F[Fix and retry] F --> C ``` `session.ts` backs `spana hierarchy` and `spana selectors`. `Session.selectors()` dumps the element tree, flattens it, and returns only visible elements with a `testID`, `accessibilityLabel`, or `text` — each annotated with the best-priority selector to use in a flow file. ## Monorepo structure ```mermaid graph TD Root[spana/] Root --> Packages[packages/] Root --> Apps[apps/] Packages --> PProvPkg[spana/ — core library and CLI] Packages --> Config[config/ — shared TS/lint config] Packages --> Env[env/ — environment helpers] Packages --> UI[ui/ — shared UI components] Apps --> Web[web/ — web app under test] Apps --> Native[native/ — React Native app under test] Apps --> TUI[tui/ — terminal UI] Apps --> Docs[docs/] PProvPkg --> Src[src/] Src --> API[api/ — flow, app, expect user API] Src --> Core[core/ — engine, orchestrator, parallel, runner] Src --> Smart[smart/ — coordinator, auto-wait, element-matcher] Src --> Drivers[drivers/ — raw-driver interface + platform impls] Src --> Agent[agent/ — session.ts for agent/CLI inspection] Src --> CLI2[cli/ — CLI entry point] Src --> Device[device/ — ADB, simctl device discovery] Src --> Report[report/ — console, json, junit, html reporters] Src --> Schemas[schemas/ — Element, Selector, DeviceInfo types] ``` --- ## Drivers All platform interaction in spana flows through the `RawDriverService` interface. Platform-specific drivers implement this interface as thin HTTP clients. No selection logic, no auto-wait, no retry — just raw platform calls. ## RawDriverService interface ```ts interface RawDriverService { tapAtCoordinate(x: number, y: number): Effect.Effect; swipe(direction: Direction, opts?: { duration?: number }): Effect.Effect; inputText(text: string): Effect.Effect; pressKey(key: string): Effect.Effect; hideKeyboard(): Effect.Effect; dumpHierarchy(): Effect.Effect; launchApp(appId: string, opts?: LaunchOptions): Effect.Effect; stopApp(appId: string): Effect.Effect; killApp(appId: string): Effect.Effect; clearAppState(appId: string): Effect.Effect; openLink(url: string): Effect.Effect; back(): Effect.Effect; takeScreenshot(): Effect.Effect; } ``` The Smart Layer (`coordinator.ts`, `auto-wait.ts`, `element-matcher.ts`) is the only consumer of this interface. Flow authors never interact with it directly. ## Driver architecture ```mermaid graph LR subgraph CLI process [CLI process — Bun/TS] RD[RawDriverService] end subgraph Android UA2[UiAutomator2 APK server\nport 6790 on device\nADB-forwarded to host] end subgraph iOS WDA[WebDriverAgent XCTest\nport 8100+ on simulator\niproxy-forwarded to host] end subgraph Web PW[Playwright / Chromium\nCDP in-process] end RD -- HTTP --> UA2 RD -- HTTP --> WDA RD -. CDP .-> PW ``` ## Web driver (Playwright) The web driver uses [Playwright](https://playwright.dev)'s CDP API in-process. No separate server is involved. - Playwright is a dev dependency — no companion binary to install or manage. - The driver launches a Chromium instance, navigates to `apps.web.url`, and exposes the page via the `RawDriverService` interface. - `dumpHierarchy()` uses Playwright's accessibility tree snapshot and returns it as structured JSON. - Coordinate taps are issued via `page.mouse.click(x, y)`. ## Android driver (UiAutomator2) The Android driver is a pure HTTP client that talks to the UiAutomator2 APK server running on the device. **Setup sequence:** 1. spana pushes the bundled UiAutomator2 APK to the device via ADB if not already installed. 2. It starts the server on the device (port 6790). 3. ADB port-forwarding maps device port 6790 to a local port. 4. The driver sends HTTP requests to `http://localhost:`. **Key endpoints:** - `GET /source` — returns the full UI hierarchy as XML - `POST /touch/perform` — performs a touch action at coordinates - `POST /appium/app/launch` — launches the app by package name The driver parses the XML hierarchy in TypeScript and produces the unified `Element` tree. No XML parsing happens in the APK. ## iOS driver (WebDriverAgent) The iOS driver is a pure HTTP client that talks to the WebDriverAgent (WDA) XCTest bundle running on the simulator or device. **Simulator setup:** 1. spana installs the bundled unsigned WDA bundle into the simulator. 2. It launches WDA (which starts an HTTP server on port 8100+). 3. The driver sends HTTP requests to `http://localhost:8100`. **Device setup:** 1. The WDA bundle must be re-signed with a user development certificate via `codesign`. 2. `iproxy` forwards the device port to a local port. 3. The driver connects to the forwarded port. **Key endpoints:** - `GET /source` — returns the full accessibility tree as JSON or XML - `POST /session/:id/element/:id/click` — taps an element - `POST /wda/touch/perform` — performs a touch at coordinates ## Hierarchy parsing Each platform returns a different hierarchy format: | Platform | Format | Parser location | | -------- | ------------------------------------ | ------------------------------------ | | Android | XML (UiAutomator ViewHierarchy) | `src/drivers/uiautomator2/parser.ts` | | iOS | JSON (WDA accessibility tree) | `src/drivers/wda/parser.ts` | | Web | JSON (Playwright accessibility tree) | `src/drivers/playwright/parser.ts` | All parsers output the same unified `Element` type: ```ts interface Element { role?: string; testID?: string; text?: string; accessibilityLabel?: string; bounds: { x: number; y: number; width: number; height: number }; children: Element[]; } ``` `element-matcher.ts` in the Smart Layer searches this tree for the selector — no platform-specific code required. ## Inspiration The thin HTTP client approach used by the WDA and UiAutomator2 drivers was inspired by [maestro-runner](https://github.com/nicklassuperset/maestro-runner), a Go project that demonstrated how minimal HTTP clients can effectively drive device interaction without heavy abstractions. The web driver follows a similar philosophy, using Playwright's CDP API directly rather than wrapping it in additional layers. --- ## Device Setup Spana auto-discovers available devices for each platform. This guide covers how to set up and verify your devices before running tests. ## Checking available devices ```bash spana devices ``` This lists all discovered devices across your configured platforms: ``` Platform ID Name Type web playwright-chromium Chromium (Playwright) browser android emulator-5554 emulator-5554 emulator ios 7338EC82-D2BD-4722-B148-D009FDA64F6E iPhone 16 (iOS 18.4) simulator ``` ## Web (Playwright) Web testing works out of the box -- Playwright manages its own Chromium browser. No setup required. Spana always shows `playwright-chromium` as an available web device. ## Android Spana discovers Android devices through `adb` (Android Debug Bridge). ### Prerequisites - **Android SDK** -- install via [Android Studio](https://developer.android.com/studio) or the command-line tools - **ADB** -- included in the Android SDK platform tools - **Java 17+** -- required by UiAutomator2 ### Using an emulator ```bash # List available AVDs emulator -list-avds # Start an emulator emulator -avd Pixel_7_API_34 & # Verify it appears adb devices # emulator-5554 device ``` ### Using a physical device 1. Enable **Developer Options** on the device 2. Enable **USB Debugging** in Developer Options 3. Connect via USB and accept the debugging prompt 4. Verify: `adb devices` should show your device serial ### Targeting a specific device When multiple Android devices are connected: ```bash # Use the --device flag with the serial from `spana devices` spana test --platform android --device emulator-5554 ``` ## iOS Spana discovers booted iOS simulators through Xcode's `simctl`. ### Prerequisites - **Xcode** -- install from the Mac App Store - **Xcode Command Line Tools** -- `xcode-select --install` - **A booted simulator** -- spana only discovers simulators that are already running ### Booting a simulator ```bash # List all available simulators xcrun simctl list devices available # Boot a simulator xcrun simctl boot "iPhone 16" # Or open the Simulator app open -a Simulator ``` ### Targeting a specific simulator ```bash # Use the UDID from `spana devices` spana test --platform ios --device 7338EC82-D2BD-4722-B148-D009FDA64F6E ``` ### Physical iOS devices Physical iOS device testing requires additional signing configuration in your config: ```ts title="spana.config.ts" export default defineConfig({ apps: { ios: { bundleId: "com.example.myapp", signing: { teamId: "YOUR_TEAM_ID", signingId: "Apple Development", provisioningProfile: "path/to/profile.mobileprovision", }, }, }, }); ``` ## Multi-device testing Run the same flows on multiple devices simultaneously: ```bash # Run on a specific Android and iOS device spana test \ --platform android,ios \ --device emulator-5554 \ --device 7338EC82-D2BD-4722-B148-D009FDA64F6E ``` When no `--device` flag is provided, spana uses the first available device for each platform. ## Troubleshooting ### Android: "no devices found" - Check `adb devices` shows your device with state `device` (not `offline` or `unauthorized`) - Restart ADB: `adb kill-server && adb start-server` - For emulators, ensure the emulator is fully booted (wait for the home screen) ### iOS: "no simulators found" - Spana only discovers **booted** simulators -- make sure one is running - Check: `xcrun simctl list devices booted` - If empty, boot one: `xcrun simctl boot "iPhone 16"` ### iOS: WebDriverAgent build fails - Open `WebDriverAgent.xcodeproj` in Xcode and resolve signing issues - Ensure your Xcode version matches the simulator runtime - Try: `xcodebuild -showsdks` to verify available SDKs --- ## Remote Execution By default, spana runs tests locally using built-in drivers (Playwright for web, UiAutomator2 for Android, WebDriverAgent for iOS). Switch to **Appium mode** to run against a remote Appium server — useful for cloud device farms, shared test infrastructure, or devices on another machine. ## Enabling Appium mode ### Config file ```ts title="spana.config.ts" export default defineConfig({ execution: { mode: "appium", appium: { serverUrl: "http://localhost:4723", }, }, }); ``` ### CLI flags ```bash spana test --appium-url http://localhost:4723 ``` The `--appium-url` flag automatically enables Appium mode. ## How it works In Appium mode, spana: 1. Connects to the Appium server at the given URL 2. Creates a session with the resolved [capabilities](#capabilities) 3. Runs your flows using the Appium WebDriver protocol instead of local drivers 4. Deletes the session when the run completes 5. Reports results to the [cloud provider](/guides/cloud-providers) if detected The same flow files work in both local and Appium mode -- no changes needed. ## Cloud helper config For BrowserStack and Sauce Labs, Spana can also manage provider-specific helper behavior on top of raw capabilities: - upload a local app artifact and inject `appium:app` - start and stop BrowserStack Local / Sauce Connect - fill missing `bstack:options` / `sauce:options` values from config Raw capabilities still win. Helper config fills missing provider fields and lifecycle, but it does not override explicit `appium:app`, `bstack:options`, or `sauce:options` values you already provided through config, `--caps`, or `--caps-json`. ## Capabilities Appium sessions are configured through W3C capabilities. Spana merges capabilities from three sources (later overrides earlier): | Source | How to set | Example | | ----------- | ----------------------------------------------- | ------------------------------------ | | Config file | `execution.appium.capabilities` | `{ "appium:app": "/path/to/app" }` | | JSON file | `--caps ` or `capabilitiesFile` in config | `caps.json` | | Inline CLI | `--caps-json ''` | `'{"appium:deviceName": "Pixel 7"}'` | ### Android capabilities ```json title="caps-android.json" { "appium:automationName": "UiAutomator2", "appium:deviceName": "emulator-5554", "appium:app": "/path/to/app.apk", "appium:appPackage": "com.example.myapp", "appium:appActivity": "com.example.myapp.MainActivity" } ``` Spana automatically sets `platformName: "Android"`. ### iOS capabilities ```json title="caps-ios.json" { "appium:automationName": "XCUITest", "appium:deviceName": "iPhone 15", "appium:platformVersion": "18.0", "appium:app": "/path/to/app.ipa", "appium:bundleId": "com.example.myapp" } ``` Spana automatically sets `platformName: "iOS"` and `appium:automationName: "XCUITest"`. ## Local Appium server To test against a local Appium server: ```bash # Install Appium npm install -g appium # Install drivers appium driver install uiautomator2 appium driver install xcuitest # Start the server appium # Run tests against it spana test --appium-url http://localhost:4723 ``` ## Config reference ```ts title="spana.config.ts" export default defineConfig({ execution: { mode: "appium", appium: { // Appium server URL (required in appium mode) serverUrl: "http://localhost:4723", // Inline capabilities (lowest priority) capabilities: { "appium:app": "/path/to/app.apk", }, // Path to a JSON capabilities file (medium priority) capabilitiesFile: "./caps.json", // Report results to cloud provider (default: true) reportToProvider: true, // BrowserStack helper config browserstack: { app: { path: "./builds/app.apk", customId: "spana-android" }, local: { enabled: true, identifier: "spana-local" }, options: { projectName: "my-app", buildName: "ci-42", }, }, // Sauce Labs helper config saucelabs: { app: { path: "./builds/app.apk", name: "app.apk" }, connect: { enabled: true, tunnelName: "spana-ci" }, options: { build: "ci-42", name: "login-flow", }, }, }, }, }); ``` ## CLI flags | Flag | Description | | ------------------------- | --------------------------------------- | | `--appium-url ` | Appium server URL (enables appium mode) | | `--caps ` | Path to capabilities JSON file | | `--caps-json ` | Inline capabilities JSON string | | `--no-provider-reporting` | Disable cloud provider result reporting | ## Cloud providers When the Appium URL points to BrowserStack or Sauce Labs, spana auto-detects the provider and reports test results. See the [Cloud Providers](/guides/cloud-providers) guide for setup details. --- ## Cloud Providers Spana can run mobile tests on cloud device farms through Appium. It auto-detects BrowserStack and Sauce Labs from the server URL, reports test results back to the provider dashboard, and can manage provider-specific upload/tunnel helpers from config. ## Supported providers | Provider | Auto-detected | Result reporting | Managed helpers | | ------------ | ------------- | ---------------- | --------------- | | BrowserStack | Yes | Yes | Yes | | Sauce Labs | Yes | Yes | Yes | | Custom grid | -- | No | No | ## BrowserStack ### 1. Set your credentials Embed credentials in the Appium server URL: ```ts title="spana.config.ts" export default defineConfig({ execution: { mode: "appium", appium: { serverUrl: "https://USER:KEY@hub-cloud.browserstack.com/wd/hub", }, }, }); ``` Or pass them on the CLI: ```bash spana test --appium-url "https://USER:KEY@hub-cloud.browserstack.com/wd/hub" ``` ### 2. Set capabilities or helper config Create a `caps.json` file with BrowserStack-specific options: ```json title="caps.json" { "bstack:options": { "projectName": "my-app", "buildName": "ci-42", "deviceName": "Samsung Galaxy S23", "os_version": "13.0" }, "appium:app": "bs://app-id-from-upload" } ``` Then reference it: ```bash spana test --caps caps.json ``` Or let Spana manage app upload, BrowserStack Local, and default `bstack:options` values from config: ```ts title="spana.config.ts" export default defineConfig({ apps: { android: { packageName: "com.example.myapp", appPath: "./builds/app.apk", }, }, execution: { mode: "appium", appium: { serverUrl: "https://USER:KEY@hub-cloud.browserstack.com/wd/hub", browserstack: { app: { customId: "spana-android", }, local: { enabled: true, identifier: "spana-local", }, options: { projectName: "my-app", buildName: process.env.CI_BUILD_ID ?? "local", }, }, capabilities: { "appium:deviceName": "Samsung Galaxy S23", "appium:platformVersion": "13.0", }, }, }, }); ``` Use `browserstack.app.id` when you already have a `bs://...` reference. If `appium:app` or `bstack:options` are already set in raw capabilities, those explicit values win and helper config only fills what is missing. ### 3. Result reporting Spana automatically reports pass/fail status to BrowserStack when a test run completes. This updates the session in the BrowserStack dashboard with the test name, status, and failure reason. Disable reporting with `--no-provider-reporting` or in config: ```ts appium: { reportToProvider: false, } ``` When `browserstack.local.enabled` is true, Spana starts and stops BrowserStack Local for the run. Set `browserstack.local.binary` if the `BrowserStackLocal` binary is not on `PATH`, or keep managing the tunnel yourself and pass `bstack:options.local` manually. ## Sauce Labs ### 1. Set your credentials ```ts title="spana.config.ts" export default defineConfig({ execution: { mode: "appium", appium: { serverUrl: "https://USER:KEY@ondemand.us-west-1.saucelabs.com/wd/hub", }, }, }); ``` For EU data center: ```bash spana test --appium-url "https://USER:KEY@ondemand.eu-central-1.saucelabs.com/wd/hub" ``` ### 2. Set capabilities or helper config ```json title="caps.json" { "sauce:options": { "name": "login-flow", "build": "ci-42", "appiumVersion": "2.0" }, "appium:deviceName": "Google Pixel 7", "appium:platformVersion": "13", "appium:app": "storage:filename=app.apk" } ``` Or let Spana manage Sauce storage uploads, Sauce Connect, and default `sauce:options` values from config: ```ts title="spana.config.ts" export default defineConfig({ apps: { android: { packageName: "com.example.myapp", appPath: "./builds/app.apk", }, }, execution: { mode: "appium", appium: { serverUrl: "https://USER:KEY@ondemand.us-west-1.saucelabs.com/wd/hub", saucelabs: { app: { name: "app.apk", }, connect: { enabled: true, tunnelName: "spana-ci", }, options: { build: process.env.CI_BUILD_ID ?? "local", name: "login-flow", }, }, capabilities: { "appium:deviceName": "Google Pixel 7", "appium:platformVersion": "13", }, }, }, }); ``` Use `saucelabs.app.id` when you already have a Sauce storage reference such as `storage:YOUR_APP_ID`. Explicit `appium:app` and `sauce:options` capability values still override helper-derived defaults. ### 3. Result reporting Sauce Labs sessions are automatically updated with pass/fail status after each test. Region (US/EU) is detected from the server URL. When `saucelabs.connect.enabled` is true, Spana starts and stops Sauce Connect for the run. Set `saucelabs.connect.binary` if the `sc` binary is not on `PATH`, or keep managing the tunnel yourself and pass `sauce:options.tunnelName` manually. ## Capability resolution Capabilities merge from three sources, with later sources overriding earlier ones: 1. **Config file** -- `execution.appium.capabilities` in `spana.config.ts` 2. **Capabilities file** -- `--caps ` flag or `execution.appium.capabilitiesFile` in config 3. **Inline CLI JSON** -- `--caps-json '{"key": "value"}'` This lets you keep shared capabilities in config, environment-specific ones in a file, and override individual values from the CLI. ## Custom cloud providers If you use an Appium grid other than BrowserStack or Sauce Labs, point `execution.appium.cloudProvider` at a module that default-exports a `CloudProvider`. ```ts title="spana.config.ts" export default defineConfig({ execution: { mode: "appium", appium: { serverUrl: "https://grid.example.com/wd/hub", cloudProvider: "./providers/acme-grid.ts", }, }, }); ``` The module path is resolved relative to `spana.config.ts`. ### `CloudProvider` ```ts import type { CloudProvider, CloudProviderHelper } from "spana-test"; const provider: CloudProvider = { name() { return "Acme Grid"; }, createHelper(appiumUrl, config): CloudProviderHelper { return { async prepareCapabilities(platform, caps, appConfig) { return { ...caps, "acme:options": { platform, appIdentifier: appConfig?.packageName ?? appConfig?.bundleId, }, }; }, async cleanup() { // stop tunnels, delete temporary uploads, etc. }, }; }, extractMeta(sessionId, caps, meta) { meta.sessionId = sessionId; meta.build = String(caps["build"] ?? ""); }, async reportResult(appiumUrl, meta, result) { await fetch(`${appiumUrl}/custom-results/${meta.sessionId}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(result), }); }, }; export default provider; ``` ### Interface responsibilities | API | Responsibility | | ----------------------- | ------------------------------------------------------------------ | | `name()` | Human-readable provider name | | `createHelper()` | Build a helper for capability mutation and lifecycle cleanup | | `prepareCapabilities()` | Add provider-specific desired capabilities before session creation | | `cleanup()` | Tear down uploads, tunnels, or temporary state after the run | | `extractMeta()` | Pull provider metadata from the created session for reporting | | `reportResult()` | Mark the remote session passed or failed | ## CI example ```yaml title=".github/workflows/test.yml" jobs: e2e: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: oven-sh/setup-bun@v2 - run: bun install - run: | spana test \ --platform android \ --appium-url "https://${{ secrets.BS_USER }}:${{ secrets.BS_KEY }}@hub-cloud.browserstack.com/wd/hub" \ --caps caps.json \ --caps-json '{"bstack:options": {"buildName": "${{ github.run_id }}"}}' ``` --- ## CI/CD Integration spana is designed for CI from the ground up. It ships as a single npm package (`spana-test`), produces machine-readable output via JSON and JUnit reporters, and uses standard exit codes so your pipeline can react to results without parsing logs. ## Exit codes | Code | Meaning | | ---- | ----------------- | | `0` | Command succeeded | | `1` | Command failed | ## Reporters for CI Use the `--reporter` flag to control output format. Multiple reporters can be combined with commas. ```bash # Machine-readable results for CI dashboards spana test --reporter json,junit # Human-readable HTML report for review spana test --reporter html # Combined: console output + JUnit + HTML spana test --reporter console,junit,html ``` - **`junit`** — writes a JUnit XML file to `spana-output/junit.xml`, understood by most CI systems. - **`json`** — writes structured JSON to stdout, useful for piping to other tools. - **`html`** — writes an HTML report to `spana-output/report.html` with screenshots and step details. ## GitHub Actions ### Using the reusable action Spana provides a composite GitHub Action that handles installation, test execution, and artifact upload: ```yaml name: E2E Tests on: [push, pull_request] jobs: e2e-web: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - run: npm ci - run: npm run dev & - run: npx wait-on http://localhost:3000 - name: Run E2E tests uses: ./.github/actions/spana-test with: platform: web reporters: console,junit,html e2e-android: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - run: npm ci - name: Set up Android emulator uses: reactivecircus/android-emulator-runner@v2 with: api-level: 33 script: echo "Emulator ready" - name: Run E2E tests uses: ./.github/actions/spana-test with: platform: android retries: 1 e2e-ios: runs-on: macos-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - run: npm ci - name: Boot iOS Simulator run: | xcrun simctl boot "iPhone 15" xcrun simctl bootstatus "iPhone 15" -b - name: Run E2E tests uses: ./.github/actions/spana-test with: platform: ios ``` #### Action inputs | Input | Default | Description | | ------------------ | -------------------- | --------------------------------------- | | `platform` | `web` | Platform to test (web, android, ios) | | `reporters` | `console,junit,html` | Comma-separated reporter names | | `config` | — | Path to spana.config.ts | | `flow-path` | — | Path to flow files or directory | | `device` | — | Target a specific device by ID | | `retries` | — | Number of retries for failed flows | | `tags` | — | Filter by tags | | `grep` | — | Filter by name pattern | | `upload-artifacts` | `true` | Upload spana-output/ as build artifacts | ### Manual workflow setup If you prefer full control over the workflow steps: ```yaml name: E2E Tests (Web) on: [push, pull_request] jobs: e2e-web: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - name: Install dependencies run: npm ci - name: Install spana run: npm install -g spana-test - name: Start app run: npm run dev & - name: Wait for app run: npx wait-on http://localhost:3000 - name: Run tests run: spana test --platform web --reporter console,junit,html - name: Upload JUnit results if: always() uses: actions/upload-artifact@v4 with: name: junit-results path: spana-output/junit.xml - name: Upload HTML report if: always() uses: actions/upload-artifact@v4 with: name: html-report path: spana-output/report.html - name: Upload screenshots if: always() uses: actions/upload-artifact@v4 with: name: screenshots path: spana-output/screenshots/ ``` ### Android tests Android tests need the Android SDK. GitHub's `ubuntu-latest` runners include the SDK, but you need to boot an emulator. ```yaml e2e-android: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - name: Install spana run: npm install -g spana-test - name: Set up Android emulator uses: reactivecircus/android-emulator-runner@v2 with: api-level: 33 script: | adb wait-for-device spana test --platform android --reporter console,junit,html - name: Upload test artifacts if: always() uses: actions/upload-artifact@v4 with: name: android-results path: spana-output/ ``` ### iOS tests iOS tests require a macOS runner with Xcode installed. ```yaml e2e-ios: runs-on: macos-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - name: Install spana run: npm install -g spana-test - name: Boot iOS Simulator run: | xcrun simctl boot "iPhone 15" xcrun simctl bootstatus "iPhone 15" -b - name: Install app and run tests run: spana test --platform ios --reporter console,junit,html - name: Upload test artifacts if: always() uses: actions/upload-artifact@v4 with: name: ios-results path: spana-output/ ``` ## GitLab CI ```yaml e2e-web: image: node:20 stage: test script: - npm ci - npm install -g spana-test - npm run dev & - npx wait-on http://localhost:3000 - spana test --platform web --reporter console,junit,html artifacts: when: always paths: - spana-output/ reports: junit: spana-output/junit.xml ``` GitLab natively parses JUnit XML when declared under `artifacts.reports.junit`, so test results appear directly in merge request widgets. ## Tips - **Combine reporters.** Use `--reporter console,junit,html` to get terminal output for logs, JUnit for CI dashboards, and HTML for manual review — all in one run. - **Upload `spana-output/` as artifacts.** This directory contains JUnit XML, HTML reports, and screenshots from failed steps. Always upload with `if: always()` (GitHub Actions) or `when: always` (GitLab) so artifacts are available even when tests fail. - **Headless web works out of the box.** Playwright runs headless by default. No `xvfb` or display server setup needed. - **Use tags to split pipelines.** Run `spana test --tag smoke` on every push and `spana test --tag regression` on a nightly schedule to balance speed and coverage. - **Pin spana version.** Use `npm install -g spana-test@0.1.0` in CI to avoid unexpected breakage from new releases. --- ## Debugging When a test fails, spana can drop you into an interactive REPL connected to the live device session. This lets you inspect the screen, try selectors, and experiment with actions before the session is torn down. ## Enabling the debug REPL ```bash spana test --debug-on-failure ``` When a flow fails, instead of moving to the next flow, spana pauses and opens a REPL: ``` Entering debug REPL for failed flow "login flow" on android. Available bindings: app, expect, driver, platform, flowName, error, hierarchy(), selectors(), help() Use top-level await for async calls, for example: await app.tap({ text: "Login" }) spana:android> ``` ## Available bindings | Binding | Type | Description | | ------------- | -------- | ---------------------------------------------------- | | `app` | object | Full `PromiseApp` API -- tap, inputText, scroll, etc | | `expect` | function | Assertion helper, same as in flows | | `driver` | object | Raw driver service for low-level access | | `platform` | string | Current platform (`"web"`, `"android"`, `"ios"`) | | `flowName` | string | Name of the failed flow | | `error` | Error | The error that caused the failure | | `hierarchy()` | async | Returns the parsed UI element tree | | `selectors()` | async | Returns suggested selectors for visible elements | | `help()` | function | Print all available bindings | ## Example session ``` spana:android> error.message 'Timed out waiting for selector { testID: "welcome-text" }' spana:android> await selectors() [ { suggestedSelector: { testID: 'login-button' }, elementType: 'Button', text: 'Sign In' }, { suggestedSelector: { text: 'Welcome' }, elementType: 'Text', text: 'Welcome' }, ... ] spana:android> await app.tap({ text: "Sign In" }) undefined spana:android> await expect({ testID: "welcome-text" }).toBeVisible() undefined spana:android> .exit ``` ## Tips - Use `await selectors()` to discover what's on screen -- this is the fastest way to find the right selector - Use `await hierarchy()` for the full element tree with bounds, visibility, and nesting - All `app` methods use auto-wait, so `await app.tap(...)` will retry until the element appears - The REPL only activates once per test run (the first failure) to avoid blocking CI - The REPL requires an interactive terminal (TTY) -- it's skipped automatically in CI environments - Type `.exit` or press `Ctrl+D` to leave the REPL and continue the test run