diff --git a/AGENTS.md b/AGENTS.md index b7c299a..b6f30e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,6 +40,7 @@ Keep device-backend details in the appropriate driver and shared contracts in `p - Dependency changes in `package.json` require a matching regenerated `package-lock.json`; registry versions must exist on npm. - New dependencies, telemetry, or runtime network behavior require an issue and maintainer approval. This rule concerns product changes, not research or normal development tooling. - Update user-facing documentation with behavior changes. Do not edit `CHANGELOG.md`; maintainers write it at release time. +- Present Mobilewright as mobile automation and testing, with four primary workflows: Test, CLI, MCP, and Library. ## Tests and verification diff --git a/README.md b/README.md index 7c4b887..b976db8 100644 --- a/README.md +++ b/README.md @@ -4,600 +4,452 @@ [![License](https://img.shields.io/badge/License-Apache%202.0-blue?style=flat-square)](LICENSE) [![TypeScript](https://img.shields.io/badge/TypeScript-5.4+-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/) -Framework for mobile device automation, inspired by Playwright's architecture and developer experience. +**Mobilewright is a framework for mobile automation and testing.** Control iOS and Android devices, simulators, and emulators from tests, scripts, coding agents, and MCP clients, with a developer experience inspired by Playwright. -**Mobilewright** targets iOS and Android devices, simulators, and emulators through a clean, auto-waiting API built on top of [mobilecli](https://github.com/mobile-next/mobilecli). +[Get Started](#get-started) · [API Examples](#api-at-a-glance) · [Documentation](https://mobilewright.dev/docs/) · [API Reference](#api-reference) · [Roadmap](ROADMAP.md) · [Mobile Next Cloud](https://mobilenext.ai/cloud?utm_source=github&utm_medium=readme&utm_campaign=mobilewright&utm_content=hero) -[Get Started](#quick-start) · [API Docs](#api-reference) · [Roadmap](ROADMAP.md) · [Mobile Next Cloud](https://mobilenext.ai/cloud?utm_source=github&utm_medium=readme&utm_campaign=mobilewright&utm_content=hero) +## Get Started -![One Mobilewright test running on an iPhone and an Android phone side by side](https://raw.githubusercontent.com/mobile-next/mobilewright/main/docs/src/images/cart-test.gif) +Choose the path that fits your workflow: -## Quick Start +| | Best for | Install / start | +|---|---|---| +| [Mobilewright Test](#mobilewright-test) | End-to-end mobile testing | `npm init mobilewright@latest` | +| [Mobilewright CLI](#mobilewright-cli) | Coding agents and terminal automation | `npm install -g @mobilewright/cli@latest` | +| [Mobilewright MCP](#mobilewright-mcp) | AI agents using structured tools | `npx -y @mobilewright/mcp@latest` | +| [Mobilewright Library](#mobilewright-library) | Mobile automation scripts | `npm install mobilewright` | -```bash -npm install mobilewright @mobilewright/test -npx mobilewright init -``` +## Prerequisites -```typescript -import { test, expect } from '@mobilewright/test'; +All four workflows require **Node.js 22.12 or newer**. For local automation, have a booted simulator or emulator, or a connected device ready before you start: -test('can sign in', async ({ screen }) => { - await screen.getByLabel('Email').fill('user@example.com'); - await screen.getByLabel('Password').fill('password123'); - await screen.getByRole('button', { name: 'Sign In' }).tap(); +- **iOS:** macOS with Xcode and the Command Line Tools. Boot an iOS simulator, or connect and trust a real iPhone. +- **Android:** a JDK and the Android SDK, with `ANDROID_HOME` set and `adb` on your `PATH`. Start an emulator, or connect a device with USB debugging enabled and authorized. +- **Your app:** install a build on the device and note its bundle ID (iOS) or package name (Android). The examples use `com.example.myapp`; replace it with your app's ID and adapt the labels and expected text to your app. - await expect(screen.getByText('Welcome back')).toBeVisible(); -}); -``` +Check your local environment and available devices: ```bash -npx mobilewright test +npx mobilewright doctor +npx mobilewright devices ``` -## Features - -- **Playwright-style API** — `screen.getByRole('button').tap()`, just like `page.getByRole('button').click()` -- **Zero config** — auto-discovers booted simulators -- **Cross-platform** — unified interface for iOS and Android -- **Auto-waiting** — actions wait for elements to be visible, enabled, and stable before interacting -- **Chainable locators** — `screen.getByType('Cell').getByLabel('Item 1')` -- **Retry assertions** — `expect(locator).toBeVisible()` polls until satisfied or timeout -- **Remote support** — connect to mobilecli on another machine for device lab setups -- **Test fixtures** — `@mobilewright/test` extends Playwright Test with `screen` and `device` fixtures - -## Why Mobilewright? +Mobilewright includes [mobilecli](https://github.com/mobile-next/mobilecli) for local device control. The `doctor` command reports missing dependencies and how to fix them. -If you've used Playwright, you already know Mobilewright. +For a real iPhone, install the device agent using a development provisioning profile that includes your device and a matching signing certificate with its private key in your Mac's keychain: -| | Mobilewright | Appium | Detox | XCTest/Espresso | -|---|---|---|---|---| -| API style | Playwright (`getByRole`, `expect`) | Selenium (WebDriver) | Custom | Native framework | -| Auto-wait | Built-in, every action | Manual waits | Partial | Manual | -| Setup | `npm install mobilewright` | Server + drivers + caps | React Native only | Xcode/AS only | -| Cross-platform | iOS + Android, one API | Yes, verbose | React Native only | Single platform | -| AI agent support | First-class (accessibility tree) | Limited | No | No | -| Real devices in the cloud | [Mobile Next Cloud](https://mobilenext.ai/cloud?utm_source=github&utm_medium=readme&utm_campaign=mobilewright&utm_content=comparison), [BrowserStack](https://mobilewright.dev/docs/cloud-providers/browserstack), [Sauce Labs](https://mobilewright.dev/docs/cloud-providers/saucelabs), [TestMu AI](https://mobilewright.dev/docs/cloud-providers/testmu), [TestingBot](https://mobilewright.dev/docs/cloud-providers/testingbot) | Yes (complex) | Simulators only | Yes | -| Locators | Semantic roles + labels | XPath, CSS, ID | Test IDs | Native queries | +```bash +npx mobilewright install --device --provisioning-profile /path/to/profile.mobileprovision +``` -## Built for AI agents +Replace `` with the ID from `devices` and the profile path with your own. See [mobilecli setup](https://github.com/mobile-next/mobilecli) for signing requirements. -Your agent needs a phone, not a screenshot. +See [Installation](https://mobilewright.dev/docs/), [Windows setup](https://mobilewright.dev/docs/getting-started/windows), [Android in Docker](https://mobilewright.dev/docs/guides/docker), and [Troubleshooting](https://mobilewright.dev/docs/guides/troubleshooting) for platform-specific instructions. Tests and library scripts can also use [cloud device providers](#run-on-real-devices-in-the-cloud); MCP supports [Mobile Next Cloud](https://github.com/mobile-next/mobile-mcp) without a local device toolchain. -Mobilewright exposes the device's accessibility tree — deterministic, token-efficient, no vision model needed. Use it with [mobile-mcp](https://github.com/mobile-next/mobile-mcp), Claude, Cursor, or any coding agent. +## Mobilewright Test -```typescript -// An AI agent can control a real phone with readable, semantic actions -await screen.getByRole('button', { name: 'Sign In' }).tap(); -await screen.getByLabel('Email').fill('user@example.com'); -await expect(screen.getByText('Welcome')).toBeVisible(); -``` +Write repeatable end-to-end tests with `@mobilewright/test`, which extends Playwright Test with mobile `device` and `screen` fixtures, auto-waiting locators, retrying assertions, and test reports. -No XPath. No coordinates. No vision model. The agent reads the accessibility tree and acts on it directly. +### Install -## Prerequisites +Scaffold a project: -- Node.js >= 22.12 -- A booted iOS simulator, Android emulator, or connected real device +```bash +npm init mobilewright@latest +``` -Run `mobilewright doctor` to verify your environment is ready: +Or add Mobilewright to an existing Node.js project: ```bash -npx mobilewright doctor +npm install --save-dev mobilewright @mobilewright/test +npx mobilewright init ``` -It checks Xcode, Android SDK, simulators, ADB, and other dependencies — and tells you exactly what's missing and how to fix it. Add `--json` for machine-readable output. +### Configure your app -## Packages +Edit the generated `mobilewright.config.ts` (or `mobilewright.config.js` if you chose JavaScript): -| Package | Description | -|---|---| -| `mobilewright` | Main entry point — `ios`, `android` launchers, `expect`, config, CLI | -| `@mobilewright/test` | Test fixtures | -| `@mobilewright/protocol` | TypeScript interfaces (`MobilewrightDriver`, `ViewNode`) | -| `@mobilewright/driver-mobilecli` | WebSocket JSON-RPC client for mobilecli | -| `@mobilewright/driver-mobilenext` | WebSocket JSON-RPC client for [Mobile Next Cloud](https://mobilenext.ai/cloud?utm_source=github&utm_medium=readme&utm_campaign=mobilewright&utm_content=packages) cloud devices | -| `@mobilewright/core` | `Device`, `Screen`, `Locator`, `expect` — the user-facing API | +```typescript +import { defineConfig } from 'mobilewright'; -Most users only need `mobilewright` (or `@mobilewright/test` for Playwright Test integration). +export default defineConfig({ + platform: 'ios', + bundleId: 'com.example.myapp', + deviceName: /iPhone/, + timeout: 30_000, +}); +``` -## API Reference +For Android, set `platform: 'android'` and change or remove `deviceName`. You can also select a specific device with `deviceId`. The app must already be installed, or you can add `installApps` with the path to a compatible build, such as an Android `.apk` or a real-device iOS `.ipa`. -### Launchers — `ios` and `android` +### Write a test -The top-level entry points. Like Playwright's `chromium` / `firefox` / `webkit`. +Replace the generated example test with this sign-in flow. Use your app's field labels, a test account, and the text shown after a successful sign-in: ```typescript -import { ios, android } from 'mobilewright'; - -// Launch with auto-discovery (finds first booted simulator) -const device = await ios.launch(); - -// Launch a specific app -const device = await ios.launch({ bundleId: 'com.example.app' }); - -// Target a specific simulator by name -const device = await ios.launch({ deviceName: /My.*iPhone/ }); +import { test, expect } from '@mobilewright/test'; -// Explicit device UDID (skips discovery) -const device = await ios.launch({ deviceId: '5A5FCFCA-...' }); +test('can sign in', async ({ screen }) => { + await screen.getByLabel('Email').fill('user@example.com'); + await screen.getByLabel('Password').fill('password123'); + await screen.getByRole('button', { name: 'Sign In' }).tap(); -// List available devices -const devices = await ios.devices(); -const devices = await android.devices(); + await expect(screen.getByText('Welcome back')).toBeVisible(); +}); ``` -`launch()` handles the full lifecycle: -1. Checks if mobilecli is reachable (auto-starts it for local URLs if not running) -2. Discovers booted devices (picks the first device that matches your criteria) -3. Connects and optionally launches the app -4. On `device.close()`, kills the auto-started server - -### Screen +The fixtures connect to the configured device, restart the configured app before each test by default, and close the connection when the worker finishes. A screenshot is attached to the report when a test fails. -Entry point for finding and interacting with elements. Access via `device.screen`. +### Run tests -**Locator factories:** - -```typescript -screen.getByLabel('Email') // accessibility label -screen.getByTestId('login-button') // accessibility identifier -screen.getByText('Welcome') // visible text (exact match) -screen.getByText(/welcome/i) // RegExp match -screen.getByText('welcome', { exact: false }) // substring match -screen.getByType('TextField') // element type -screen.getByRole('button', { name: 'Sign In' }) // semantic role + name filter -screen.getByPlaceholder('Search...') // placeholder text +```bash +npx mobilewright test ``` -**Direct actions:** +Generate and open an HTML report: -```typescript -await screen.screenshot() // capture PNG -await screen.screenshot({ format: 'jpeg', quality: 80 }) -await screen.swipe('up') -await screen.swipe('down', { distance: 300, duration: 500 }) -await screen.pressButton('HOME') -await screen.tap(195, 400) // raw coordinate tap -await screen.doubleTap(195, 400) // raw coordinate double-tap -await screen.longPress(195, 400, 1000) // raw coordinate long-press (optional duration in ms) -const tree = await screen.viewTree() // raw accessibility tree (ViewNode[]) +```bash +npx mobilewright test --reporter html +npx mobilewright show-report ``` -### Locator +![One Mobilewright test running on an iPhone and an Android phone side by side](https://raw.githubusercontent.com/mobile-next/mobilewright/main/docs/src/images/cart-test.gif) -Lazy, chainable element reference. No queries execute until you call an action or assertion. +[Writing tests](https://mobilewright.dev/docs/getting-started/writing-tests) · [Running tests](https://mobilewright.dev/docs/getting-started/running-tests) · [Configuration](https://mobilewright.dev/docs/test/configuration) · [Fixtures](https://mobilewright.dev/docs/test/fixtures) · [CI setup](https://mobilewright.dev/docs/getting-started/ci) -**Actions** (all auto-wait for the element to be visible, enabled, and have stable bounds): +## Mobilewright CLI -```typescript -await locator.tap() -await locator.doubleTap() -await locator.longPress({ duration: 1000 }) -await locator.fill('hello@example.com') // tap to focus, clear, then type text -await locator.clear() // tap to focus + clear the field -await locator.check() // checkbox / radio / switch: tap only if not already checked -await locator.uncheck() // tap only if currently checked -await locator.setChecked(true) // check() or uncheck() by value -await locator.swipe({ direction: 'left' }) // swipe on a specific element -await locator.scrollIntoViewIfNeeded() // scroll until element is visible -await locator.screenshot() // capture just this element (cropped PNG) -``` +`mobilewright-cli` lets coding agents such as Claude Code, Codex, and Cursor control mobile devices through shell commands. It returns compact accessibility snapshots with element references, and prints the corresponding Mobilewright code after actions so an explored flow can become a test. -**Narrowing & combining** — refine a locator that matches multiple elements: +### Install -```typescript -locator.filter({ hasText: 'In stock' }) // keep matches whose subtree contains text -locator.filter({ hasNotText: /sold out/i }) // keep matches whose subtree does NOT contain text -locator.filter({ has: screen.getByRole('button') }) // keep matches containing a child locator -locator.filter({ hasNot: screen.getByText('Ad') }) // keep matches NOT containing a child locator -locator.and(screen.getByRole('button')) // match both this and another locator -locator.or(screen.getByText('Retry')) // match either this or another locator +```bash +npm install -g @mobilewright/cli@latest ``` -**Multiple matches** — work with locators that resolve to more than one element: +Optionally install the bundled agent skill in your project. For Claude Code: -```typescript -locator.first() // first match -locator.last() // last match -locator.nth(2) // match at index (negative counts from the end) -await locator.count() // number of matching elements -await locator.all() // array of Locators, one per match +```bash +mobilewright-cli install ``` -**Queries:** +For agents that discover skills in `.agents/skills/`: -```typescript -await locator.exists() // boolean — present in the hierarchy (no wait) -await locator.isVisible() // boolean -await locator.isEnabled() // boolean -await locator.isSelected() // boolean -await locator.isFocused() // boolean -await locator.isChecked() // boolean -await locator.getText() // waits for visibility first -await locator.getValue() // raw value (e.g. text field content) -await locator.boundingBox() // { x, y, width, height } +```bash +mobilewright-cli install --skills agents ``` -**Explicit waiting:** +### Use from the terminal -```typescript -await locator.waitFor({ state: 'visible' }) -await locator.waitFor({ state: 'hidden' }) -await locator.waitFor({ state: 'enabled' }) -await locator.waitFor({ state: 'disabled', timeout: 10_000 }) +List devices, launch your installed app, and read the screen: + +```bash +mobilewright-cli devices +mobilewright-cli --device launch com.example.myapp +mobilewright-cli snapshot ``` -**Chaining** — scope queries within a parent element's bounds: +Replace `` with an ID from `devices`. The CLI remembers it for later commands; when exactly one device is online, you can omit `--device`. -```typescript -// Tap the delete button inside the first row -const row = screen.getByType('Cell'); -await row.getByRole('button', { name: 'Delete' }).tap(); +A sign-in screen might look like this: -// Get text from a navigation bar -const title = await screen.getByType('NavigationBar').getByType('StaticText').getText(); +```text +- textfield "Email" [ref=e7] +- textfield "Password" [ref=e8] +- button "Sign In" [ref=e9] ``` -When chaining, child lookups use bounds-based containment: any element whose bounds fit within the parent's bounds is considered a child. This works correctly with mobilecli's flat element lists. - -### WebView (hybrid apps) +Use the references from your own snapshot to interact: -Apps that embed web content — Cordova, Capacitor, Ionic, or a raw `WKWebView` / Android `WebView` — expose a real DOM behind the native view. `screen.getByWebView()` bridges into that DOM and hands you a **Playwright-compatible** `Page`, so web content is driven with the exact Playwright API you already know. +```bash +mobilewright-cli fill e7 "user@example.com" +mobilewright-cli fill e8 "password123" +mobilewright-cli tap e9 +mobilewright-cli expect visible --text "Welcome back" +mobilewright-cli screenshot -o welcome.png +``` -```typescript -// Find the web view and resolve its page (Playwright-style) -const webview = screen.getByWebView(); // optionally { testId: 'checkout-web' } -const page = await webview.page(); +References can change as the screen changes. Read the fresh snapshot after each action and use its current refs in the next command; `e7`, `e8`, and `e9` above are illustrative. To install a build first, use `mobilewright-cli app-install ./builds/myapp.apk` with the appropriate file for your device. -// From here it's the standard Playwright Page / Locator API -await page.goto('https://example.com/login'); -await page.getByLabel('Email').fill('user@example.com'); -await page.getByRole('button', { name: 'Sign In' }).click(); +### Use with a coding agent -await expect(page).toHaveURL(/dashboard/); -await expect(page.getByText('Welcome')).toBeVisible(); +```text +Use mobilewright-cli to explore the sign-in flow in com.example.myapp +on my connected device. Ask me for test credentials, verify that the +welcome screen appears, and save a screenshot. Then write the flow as +a Mobilewright test. ``` -**Page** — navigation and lifecycle: `goto`, `reload`, `goBack`, `goForward`, `url`, `title`, `content`, `waitForURL`, `waitForLoadState`, `close`. Locator factories: `locator`, `getByRole`, `getByText`, `getByLabel`, `getByPlaceholder`, `getByTestId`, `getByAltText`, `getByTitle`. +[Full CLI documentation](https://mobilewright.dev/docs/agent-cli/introduction) covers commands, device selection, named sessions, JSON output, and skill installation. -**Web Locator** — actions: `click`, `fill`, `type`, `press`, `focus`, `hover`, `scrollIntoViewIfNeeded`. Queries: `getText`, `getValue`, `textContent`, `innerText`, `innerHTML`, `inputValue`, `getAttribute`, `boundingBox`, `isVisible`, `isHidden`, `isEnabled`, `isDisabled`, `isChecked`. Plus `waitFor`, `first`/`last`/`nth`, `count`, and `all`. Assertions (`expect`) work the same as on native locators. +## Mobilewright MCP -`MobileWebViewPage` and `MobileWebViewLocator` are exported from `mobilewright` for advanced use (`Page` / `WebLocator` remain as back-compat aliases). +Mobilewright MCP gives AI agents device control through the Model Context Protocol. The `@mobilewright/mcp` package provides the [Mobile MCP server](https://github.com/mobile-next/mobile-mcp), with tools for device discovery, app installation, accessibility inspection, gestures, screenshots, and more. -### Device +### Configure your MCP client -Manages the connection lifecycle and exposes device/app-level controls. +Add this to a client that uses `mcpServers` configuration, such as Claude Desktop or Cursor: -```typescript -console.log(device.id); - -// Orientation -await device.setOrientation('landscape'); -const orientation = await device.getOrientation(); +```json +{ + "mcpServers": { + "mobilewright": { + "command": "npx", + "args": ["-y", "@mobilewright/mcp@latest"] + } + } +} +``` -// Geolocation — override the GPS location the device reports -await device.setGeolocation({ latitude: -17.833, longitude: 177.947 }); -await device.setGeolocation(null); // clear the override +Your MCP client starts the server using this command. Reconnect or restart the client after saving the configuration. Clients with a different configuration format can register the same command and arguments; see the [client setup guide](https://github.com/mobile-next/mobile-mcp#installation-and-configuration). -// Foldables — set the hinge on foldable iOS simulators and Android emulators -await device.setFoldState('half-open'); // 'folded' | 'half-open' | 'open' | 0–180 +### Try it -// Screen dimensions and pixel density: { width, height, scale } -const size = await device.screenSize(); +First ask your agent: -// URLs / deep links (goto is a Playwright-style alias for openUrl) -await device.goto('myapp://settings'); -await device.openUrl('https://example.com'); +```text +List the available mobile devices +``` -// App lifecycle -await device.launchApp('com.example.app', { locales: ['fr-FR'] }); // waits until app is in foreground -await device.launchApp('com.example.app', { noWaitAfter: true }); // skip foreground wait -await device.terminateApp('com.example.app'); -const apps = await device.listApps(); -const foreground = await device.getForegroundApp(); -await device.installApp('/path/to/app.ipa'); -await device.uninstallApp('com.example.app'); +Once your device appears, try an app workflow: -// Cleanup (disconnects + stops auto-started mobilecli) -await device.close(); +```text +Open com.example.myapp on my connected device. Inspect the sign-in screen, +ask me for test credentials, and sign in. Verify that the welcome screen +appears and save a screenshot. ``` -### Assertions — `expect` +The agent reads the device's accessibility elements to understand the screen and act on it. Screenshots and coordinate actions are also available when needed. You can then ask it to turn the flow into a repeatable Mobilewright test. -All assertions poll repeatedly until satisfied or timeout (default 5s). Supports `.not` for negation. +[MCP tools and setup](https://github.com/mobile-next/mobile-mcp) · [From an agent session to a CI test](https://mobilewright.dev/docs/guides/mobile-mcp) -```typescript -import { expect } from 'mobilewright'; +## Mobilewright Library -await expect(locator).toBeVisible(); -await expect(locator).not.toBeVisible(); -await expect(locator).toBeHidden(); +Use `mobilewright` directly in JavaScript or TypeScript scripts to automate apps, capture screenshots, and control devices. -await expect(locator).toBeEnabled(); -await expect(locator).toBeDisabled(); +### Install -await expect(locator).toBeSelected(); -await expect(locator).toBeFocused(); -await expect(locator).toBeChecked(); +```bash +npm install mobilewright +``` + +### Write a script -await expect(locator).toHaveText('Welcome back!'); -await expect(locator).toHaveText(/welcome/i); -await expect(locator).toContainText('back'); -await expect(locator).toContainText(/welcome/i); -await expect(locator).toHaveText('welcome back!', { ignoreCase: true }); // whitespace is normalized like Playwright -await expect(locator).toBeEmpty(); // element has no text +Save this as `sign-in.mjs`. It connects to an available iOS device, launches your installed app, signs in, and saves a screenshot: -await expect(locator).toHaveValue('user@example.com'); // text field / input value -await expect(locator).toHaveValue(/@example\.com$/); +```javascript +import { ios, expect } from 'mobilewright'; -await expect(locator).toHaveCount(3); // number of matching elements +const device = await ios.launch({ bundleId: 'com.example.myapp' }); -await expect(locator).toBeVisible({ timeout: 10_000 }); +try { + const screen = device.screen; + await screen.getByLabel('Email').fill('user@example.com'); + await screen.getByLabel('Password').fill('password123'); + await screen.getByRole('button', { name: 'Sign In' }).tap(); + await expect(screen.getByText('Welcome back')).toBeVisible(); + await screen.screenshot({ path: 'welcome.png' }); +} finally { + await device.close(); +} +``` -// Soft assertions record the failure but let the test keep running (Playwright semantics) -await expect.soft(locator).toHaveText('Success'); -await expect.soft(locator, 'eta should be shown').not.toBeEmpty(); +Replace the app ID, credentials, and locators with your app's values, then run: -// Retry any value matcher until it passes, and match promise rejections (Playwright semantics) -await expect.poll(() => device.getOrientation()).toBe('landscape'); -await expect(locator.tap({ timeout: 1000 })).rejects.toThrow('timed out'); +```bash +node sign-in.mjs ``` -### Role Mapping +For Android, import `android` and use `android.launch(...)`. Pass `deviceId` or a `deviceName` regular expression to choose a device, or `installApps` to install a build before launching. Library scripts pass these options directly to `launch()`. -`getByRole` maps semantic roles to platform-specific element types: +[Locators](https://mobilewright.dev/docs/guides/locators) · [Actions](https://mobilewright.dev/docs/guides/actions) · [Assertions](https://mobilewright.dev/docs/guides/assertions) · [Screenshots](https://mobilewright.dev/docs/guides/screenshots) -| Role | iOS | Android | -|---|---|---| -| `button` | Button, ImageButton | Button, ImageButton, ReactViewGroup* | -| `textfield` | TextField, SecureTextField, SearchField | EditText, ReactEditText | -| `text` | StaticText | TextView, Text, ReactTextView | -| `image` | Image | ImageView, ReactImageView | -| `switch` | Switch | Switch, Toggle | -| `checkbox` | -- | Checkbox | -| `slider` | Slider | SeekBar | -| `list` | Table, CollectionView, ScrollView | ListView, RecyclerView, ReactScrollView | -| `header` | NavigationBar | Toolbar, Header | -| `link` | Link | Link | -| `listitem` | Cell | LinearLayout, RelativeLayout, Other | -| `tab` | Tab, TabBar | Tab, TabBar | +## Features -\* ReactViewGroup matches `button` only when the element has `clickable="true"` or `accessible="true"` in its raw attributes, to avoid false positives since React Native uses ReactViewGroup for all container views. +- **iOS and Android** — automate native and hybrid apps on simulators, emulators, and real devices. +- **Playwright-style API** — `screen.getByRole('button').tap()`, chainable locators, and `expect` assertions. +- **Auto-waiting** — locator actions wait for elements to be actionable; assertions retry until satisfied or timed out. +- **Agent workflows** — use the CLI for shell-based agents or MCP for agents that call structured tools. +- **WebViews** — access embedded web content with a Playwright-compatible Page and Locator API. +- **Developer tools** — explore screens with Inspector, record tests with Codegen, and inspect results in HTML reports. +- **Remote devices** — connect to mobilecli on another machine or use a supported cloud provider. -Falls back to direct type matching if no mapping exists. +## API at a glance -## Configuration +These are independent examples to use inside a test or library script. In tests, use the `screen` and `device` fixtures and import `expect` from `@mobilewright/test`. In scripts, use `device.screen` and import `expect` from `mobilewright`, as in the [library quick start](#mobilewright-library). -Create a `mobilewright.config.ts` in your project root: +### Locators -```typescript -import { defineConfig } from 'mobilewright'; +Find native elements by what users see or by an accessibility identifier: -export default defineConfig({ - platform: 'ios', - bundleId: 'com.example.myapp', - deviceName: 'iPhone 16', - timeout: 10_000, -}); +```typescript +screen.getByText('Welcome', { exact: true }); // exact text +screen.getByText(/welcome/i); // case-insensitive RegExp match +screen.getByText('welcome', { exact: false }); // substring match +screen.getByLabel('Email'); // accessibility label +screen.getByTestId('login-button'); // accessibility identifier +screen.getByRole('button', { name: 'Sign In' }); // semantic role and name +screen.getByRole('button', { name: /sign in/i }); // role with a RegExp name +screen.getByPlaceholder('Search...'); // placeholder text ``` -All options: +Locators are lazy: creating one does not query the device. Chain and filter them to narrow a match: -| Option | Type | Description | -|---|---|---| -| `platform` | `'ios' \| 'android'` | Device platform (optional) | -| `bundleId` | `string` | App bundle ID (optional) | -| `deviceId` | `string` | Explicit device UDID (optional) | -| `deviceName` | `RegExp` | RegExp to match device name (optional) | -| `installApps` | `string \| string[]` | App paths (APK/IPA) to install before launching; relative paths resolve against the config file's directory (optional) | -| `autoAppLaunch` | `boolean` | Terminate and launch the app (`bundleId`) before each test. Default: `true` | -| `viewTree` | `'on-failure' \| 'off'` | Attach the accessibility tree as JSON to the report on failure. Default: `'off'` | -| `timeout` | `number` | Per-test timeout in ms (optional) | -| `globalTimeout` | `number` | Hard cap on the entire test suite run in ms (optional) | -| `testDir` | `string` | Directory to search for test files (optional) | -| `testMatch` | `string \| RegExp \| Array` | Glob patterns for test files (optional) | -| `testIgnore` | `string \| RegExp \| Array` | Glob patterns for files to skip during discovery (optional) | -| `outputDir` | `string` | Output directory for test artifacts. Default: `test-results` | -| `reporter` | `'list' \| 'html' \| 'json' \| 'junit' \| Array` | Reporter to use (optional) | -| `retries` | `number` | Maximum retry count for flaky tests (optional) | -| `repeatEach` | `number` | Run each test this many times. Default: `1` | -| `maxFailures` | `number` | Stop the run after this many failures. Default: `0` (no limit) | -| `failOnFlakyTests` | `boolean` | Fail the run if any test is flagged as flaky. Default: `false` | -| `workers` | `number \| string` | Number of concurrent workers (optional) | -| `fullyParallel` | `boolean` | Run all tests in parallel. Default: `false` | -| `use` | `MobilewrightUseOptions` | Per-action defaults applied to all tests (optional) | -| `expect` | `MobilewrightExpectConfig` | Default options for `expect()` assertions (optional) | -| `globalSetup` | `string \| string[]` | Setup file(s) run once before all tests (optional) | -| `globalTeardown` | `string \| string[]` | Teardown file(s) run once after all tests (optional) | -| `projects` | `MobilewrightProjectConfig[]` | Multi-device / multi-platform project matrix (optional) | - -The `use` object holds per-action defaults shared by every test: - -| `use` option | Type | Description | -|---|---|---| -| `platform` | `'ios' \| 'android'` | Platform for the run (optional) | -| `deviceId` | `string` | Specific device identifier (local drivers only) — overrides the top-level `deviceId` for this project (optional) | -| `deviceName` | `RegExp` | RegExp to match device name (optional) | -| `bundleId` | `string` | App bundle ID (optional) | -| `installApps` | `string \| string[]` | App paths to install — overrides top-level `installApps` (optional) | -| `animations` | `'on' \| 'off'` | Toggle system animations on the device; left unchanged if omitted | -| `actionTimeout` | `number` | Default timeout for locator actions (tap, fill, …) in ms. Default: `5000` | -| `appLaunchTimeout` | `number` | Timeout waiting for the app to reach foreground after launch, in ms. Default: `20000` | -| `installTimeout` | `number` | Timeout for app installation in ms. Default: `60000` | -| `allocationTimeout` | `number` | Timeout waiting for a device (queue + cloud provisioning), on its own clock. Default: `900000` (15 min) | - -The `expect` object sets assertion defaults: - -| `expect` option | Type | Description | -|---|---|---| -| `timeout` | `number` | Default timeout for assertions (`toBeVisible`, `toHaveText`, …) in ms. Default: `5000` | - -Config values are used as defaults — `LaunchOptions` passed to `ios.launch()` always take precedence. +```typescript +const cartItem = screen.getByRole('listitem').filter({ hasText: 'Milk' }); +await cartItem.getByRole('button', { name: 'Remove' }).tap(); -Mobilewright will use the first device that matches your configured criteria. +const items = screen.getByRole('listitem'); +const count = await items.count(); // current number of matches +await items.nth(1).tap(); // second item, zero-based +``` -## Test Fixtures +### Actions and assertions -`@mobilewright/test` extends [Playwright Test](https://playwright.dev/docs/test-intro) with mobile-specific fixtures: +Locator actions wait for elements to be visible, enabled, and stable before interacting: ```typescript -import { test, expect } from '@mobilewright/test'; - -// Configure the app bundle and video recording for all tests in this file -test.use({ bundleId: 'com.example.myapp', video: 'on' }); - -test('can sign in', async ({ device, screen, bundleId }) => { - // Fresh-launch the app before the test - await device.terminateApp(bundleId).catch(() => {}); - await device.launchApp(bundleId); +await screen.getByLabel('Email').fill('user@example.com'); +await screen.getByLabel('Search').clear(); +await screen.getByRole('button', { name: 'Continue' }).tap(); +await screen.getByRole('switch', { name: 'Notifications' }).check(); +await screen.getByTestId('photo').doubleTap(); +await screen.getByText('Message').longPress({ duration: 1000 }); +await screen.getByTestId('carousel').swipe({ direction: 'left' }); +await screen.getByText('Terms of service').scrollIntoViewIfNeeded(); +``` - await screen.getByLabel('Email').fill('user@example.com'); - await screen.getByLabel('Password').fill('password123'); - await screen.getByRole('button', { name: 'Sign In' }).tap(); +Assertions retry until the condition is met or the timeout expires: - await expect(screen.getByText('Welcome back')).toBeVisible(); -}); +```typescript +await expect(screen.getByText(/welcome/i)).toBeVisible(); +await expect(screen.getByText('Loading')).not.toBeVisible(); +await expect(screen.getByRole('button', { name: 'Continue' })).toBeEnabled(); +await expect(screen.getByRole('switch', { name: 'Notifications' })).toBeChecked(); +await expect(screen.getByTestId('status')).toHaveText(/ready/i); +await expect(screen.getByLabel('Email')).toHaveValue('user@example.com'); +await expect(screen.getByRole('listitem')).toHaveCount(3); ``` -The `device` fixture connects once per worker (reading from `mobilewright.config.ts`) and calls `device.close()` after all tests complete. The `screen` fixture provides `device.screen` to each test, with screenshots (on failure by default) and optional video recording. - -**`test.use()` options** — override config per file (or per `test.describe` block): +### Device lifecycle and screenshots -| Option | Type | Description | -|---|---|---| -| `bundleId` | `string` | App bundle ID for these tests | -| `platform` | `'ios' \| 'android'` | Target platform | -| `deviceId` | `string` | Specific device identifier (local drivers only) | -| `deviceName` | `RegExp` | RegExp to match the device name | -| `installApps` | `string \| string[]` | App paths (APK/IPA) to install before the tests run | -| `autoAppLaunch` | `boolean` | Terminate and launch the app (`bundleId`) before each test. Default: `true` | -| `viewTree` | `'on-failure' \| 'off'` | Attach the accessibility tree as JSON when a test fails. Default: `'off'` | -| `video` | `'on' \| 'retain-on-failure' \| 'off'` | Record video — always, only on failure, or never. Default: `'off'` | -| `screenshot` | `'on' \| 'only-on-failure' \| 'on-first-failure' \| 'off'` | Attach a device screenshot after each test, after failures, after a failure on the first try only, or never. Default: `'only-on-failure'`. Set it at the top of a file or in the config, not inside a `describe` block | +Control the app, open deep links, and capture the screen through the connected device: ```typescript -test.use({ - bundleId: 'com.example.myapp', - video: 'retain-on-failure', - screenshot: 'on', - viewTree: 'on-failure', -}); +await device.terminateApp('com.example.myapp'); +await device.launchApp('com.example.myapp'); +await device.openUrl('myapp://settings'); +await device.setOrientation('landscape'); + +await screen.screenshot({ path: 'screenshots/settings.png' }); +await screen.screenshot({ path: 'screenshots/settings.jpg', format: 'jpeg', quality: 80 }); +const image = await screen.getByTestId('profile-card').screenshot(); // cropped PNG Buffer +const size = await device.screenSize(); // { width, height, scale } ``` -## CLI +In standalone scripts, call `device.close()` in a `finally` block, as shown in the [library example](#mobilewright-library). Test fixtures manage the connection for you. Device capabilities, such as orientation and deep links, depend on the platform and driver. -### `mobilewright init` +### WebViews -Scaffold a `mobilewright.config.ts` and `example.test.ts` in the current directory. Skips files that already exist. +For a hybrid app, navigate to a screen containing an embedded WebView in a debug/development build, then use its Playwright-compatible Page and Locator APIs: -```bash -npx mobilewright init -``` +```typescript +const page = await screen.getByWebView().page(); -``` -created mobilewright.config.ts -created example.test.ts +await page.getByLabel('Email').fill('user@example.com'); +await page.getByRole('button', { name: 'Sign In' }).click(); +await expect(page).toHaveURL(/dashboard/); +await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible(); ``` -### `mobilewright devices` +Use `screen.getByWebView({ testId: 'checkout' })` to select a particular WebView. See the [WebViews guide](https://mobilewright.dev/docs/guides/webviews) for platform requirements, frames, navigation, and real touch input. -List all connected devices, simulators, and emulators. +## API Reference -```bash -npx mobilewright devices -``` +Tests and library scripts share the same device, screen, locator, and assertion APIs. Start with these guides: -``` -ID Name Platform Type State -------------------------------------------------------------------------------------------------- -00008110-0011281A112A801E VPhone ios real-device booted -5A5FCFCA-27EC-4D1B-B412-BAE629154EE0 iPhone 17 Pro ios simulator booted -``` +| API / topic | Documentation | +|---|---| +| `screen.getByRole()`, `getByLabel()`, `getByText()`, `getByTestId()` | [Locators and platform mappings](https://mobilewright.dev/docs/guides/locators) | +| `locator.tap()`, `fill()`, `swipe()`, and device actions | [Actions](https://mobilewright.dev/docs/guides/actions) | +| `expect(locator)` and retrying assertions | [Assertions](https://mobilewright.dev/docs/guides/assertions) | +| Actionability and explicit waits | [Auto-waiting](https://mobilewright.dev/docs/guides/auto-waiting) | +| `screen.screenshot()` and screenshot files | [Screenshots](https://mobilewright.dev/docs/guides/screenshots) | +| `screen.getByWebView().page()` and web locators | [WebViews](https://mobilewright.dev/docs/guides/webviews) | +| Device URLs, dialogs, and location | [Deep links](https://mobilewright.dev/docs/guides/deep-links), [Dialogs](https://mobilewright.dev/docs/guides/dialogs), [Geolocation](https://mobilewright.dev/docs/guides/geolocation) | +| `defineConfig()` and test options | [Configuration](https://mobilewright.dev/docs/test/configuration) | +| `test`, `device`, `screen`, and `test.use()` | [Test fixtures](https://mobilewright.dev/docs/test/fixtures) | +| Multiple devices, retries, and CI distribution | [Projects](https://mobilewright.dev/docs/test/projects), [Retries](https://mobilewright.dev/docs/test/retries), [Sharding](https://mobilewright.dev/docs/test/sharding) | + +## Test and utility commands + +The `mobilewright` executable ships with the library and provides test running, setup, and debugging tools. The separate [`mobilewright-cli`](#mobilewright-cli) executable provides interactive commands for coding agents. + +| Command | Purpose | +|---|---| +| `npx mobilewright init` | Create a configuration and example test; skip files that already exist | +| `npx mobilewright doctor` | Check the local environment and report missing dependencies | +| `npx mobilewright devices` | List devices, simulators, and emulators | +| `npx mobilewright install` | Install the mobilecli device agent | +| `npx mobilewright test` | Run tests using your Mobilewright configuration | +| `npx mobilewright show-report` | Open an HTML test report | +| `npx mobilewright merge-reports ./blob-reports` | Combine reports from sharded runs | +| `npx mobilewright screenshot -o home.png` | Save a device screenshot | +| `npx mobilewright inspect` | Explore a device and find locators | +| `npx mobilewright codegen` | Record device interactions as test code | -### `mobilewright inspect` +See the [command reference](https://mobilewright.dev/docs/test/cli) for options, test filtering, reporters, and parallel execution. -Open the Mobilewright Inspector — a browser-based UI showing a live screenshot of your connected device alongside every element and its best locator. +### Inspector ```bash npx mobilewright inspect -npx mobilewright inspect --port 4621 # use a specific port (default: 4621) ``` -The Inspector opens automatically in your browser. Select a device from the picker at the top, then click **Refresh** or enable **Auto refresh**. Click any row in the element list to highlight its bounding box on the screenshot. Elements that share a locator with another element get a `dup` badge. - -Locator priority matches what mobilewright uses: `getByTestId` > `getByRole` > `getByLabel` > `getByText`. +The Inspector opens in your browser with a live device screenshot and element locators. Choose a device, inspect its elements, and copy locators for your tests or scripts. ![Mobilewright Inspector](docs/src/images/inspector.png) -### `mobilewright codegen` +[Inspector guide](https://mobilewright.dev/docs/guides/inspector) -Record a test by using the device from your browser. Codegen shows a live screenshot of the connected device next to the test it is writing: every tap, device button and assertion you make is sent to the device and added as a line of code, using the same locators as the Inspector. +### Codegen ```bash npx mobilewright codegen -npx mobilewright codegen --port 8080 # use a specific port (default: a random free port) -``` - -Codegen opens in your browser automatically; its URL is also printed in the terminal in case the browser does not open. - -See the [Codegen guide](https://mobilewright.dev/docs/guides/codegen/) for recording assertions, gestures and locations. - -### `mobilewright screenshot` - -Capture a screenshot of a connected device. Auto-starts mobilecli if it isn't running. - -```bash -npx mobilewright screenshot # saves screenshot.png -npx mobilewright screenshot -o home.png # custom output path -npx mobilewright screenshot -d # target a specific device -npx mobilewright screenshot --url ws://host:12000 # remote mobilecli server -``` - -### `mobilewright install` - -Install the mobilecli agent on a connected device. - -```bash -npx mobilewright install # install on the first device -npx mobilewright install -d # target a specific device -npx mobilewright install --force # force reinstall -npx mobilewright install --provisioning-profile

# iOS provisioning profile ``` -### `mobilewright test` - -Run your tests. Auto-discovers `mobilewright.config.ts` in the current directory. +Interact with your device from the browser while Codegen records taps, gestures, and assertions as test code. -```bash -npx mobilewright test -npx mobilewright test login.test.ts # run a specific file -npx mobilewright test --grep "sign in" # filter by test name -npx mobilewright test --reporter html # generate HTML report -npx mobilewright test --retries 2 # retry flaky tests -npx mobilewright test --workers 4 # parallel workers -npx mobilewright test --repeat-each 20 # run each test 20 times -npx mobilewright test -x # stop after the first failure -npx mobilewright test --list # list tests without running -``` +[Codegen guide](https://mobilewright.dev/docs/guides/codegen) -### `mobilewright show-report` +## Packages -Open the HTML report generated by `--reporter html`. +| Package | Description | +|---|---| +| `mobilewright` | Library with `ios` and `android` launchers, `expect`, configuration, and the `mobilewright` test and utility commands | +| `@mobilewright/test` | Playwright Test integration with mobile fixtures and assertions | +| `@mobilewright/cli` | The `mobilewright-cli` executable and bundled skill for coding agents | +| `@mobilewright/mcp` | MCP server entry point powered by Mobile MCP | +| `@mobilewright/core` | `Device`, `Screen`, `Locator`, and assertion implementations | +| `@mobilewright/protocol` | Shared TypeScript driver interfaces and types | +| `@mobilewright/driver-mobilecli` | Driver for local and remote mobilecli devices | +| `@mobilewright/driver-mobilenext` | Driver for [Mobile Next Cloud](https://mobilenext.ai/cloud?utm_source=github&utm_medium=readme&utm_campaign=mobilewright&utm_content=packages) devices | -```bash -npx mobilewright show-report -npx mobilewright show-report mobilewright-report/ -``` +Install the package for your chosen workflow from [Get Started](#get-started). The core and local driver packages are included as dependencies where needed. -### `mobilewright merge-reports` +## Why Mobilewright? -Merge blob reports from sharded/parallel CI runs into a single report. +If you've used Playwright, you already know Mobilewright. -```bash -npx mobilewright merge-reports ./blob-reports # merge into an HTML report (default) -npx mobilewright merge-reports ./blob-reports --reporter json -``` +| | Mobilewright | Appium | Detox | XCTest/Espresso | +|---|---|---|---|---| +| API style | Playwright (`getByRole`, `expect`) | Selenium (WebDriver) | Custom | Native framework | +| Auto-wait | Built-in, every action | Manual waits | Partial | Manual | +| Setup | `npm install mobilewright` | Server + drivers + caps | React Native only | Xcode/AS only | +| Cross-platform | iOS + Android, one API | Yes, verbose | React Native only | Single platform | +| AI agent support | First-class (accessibility tree) | Limited | No | No | +| Real devices in the cloud | [Mobile Next Cloud](https://mobilenext.ai/cloud?utm_source=github&utm_medium=readme&utm_campaign=mobilewright&utm_content=comparison), [BrowserStack](https://mobilewright.dev/docs/cloud-providers/browserstack), [Sauce Labs](https://mobilewright.dev/docs/cloud-providers/saucelabs), [TestMu AI](https://mobilewright.dev/docs/cloud-providers/testmu), [TestingBot](https://mobilewright.dev/docs/cloud-providers/testingbot) | Yes (complex) | Simulators only | Yes | +| Locators | Semantic roles + labels | XPath, CSS, ID | Test IDs | Native queries | ## Run on real devices in the cloud @@ -611,23 +463,21 @@ The same tests that run on a local device run on real devices in the cloud. Only ## Telemetry -Mobilewright collects anonymous usage telemetry via PostHog and Scarf. To disable it, set either the `MOBILEWRIGHT_DISABLE_TELEMETRY` environment variable or the standard [`DO_NOT_TRACK`](https://consoledonottrack.com) variable: +Mobilewright collects anonymous usage telemetry via PostHog and Scarf. To disable it, set the standard [`DO_NOT_TRACK`](https://consoledonottrack.com) environment variable: ```bash -MOBILEWRIGHT_DISABLE_TELEMETRY=1 npx mobilewright test DO_NOT_TRACK=1 npx mobilewright test ``` -To opt out permanently, export one of them in your shell profile (for example `~/.zshrc` or `~/.bashrc`) or in your CI environment. +To opt out permanently, set `export DO_NOT_TRACK=1` in your shell profile (for example `~/.zshrc` or `~/.bashrc`) or set `DO_NOT_TRACK=1` in your CI environment. When telemetry is enabled, a random identifier is generated and stored in `~/.config/mobilenext/mobilewright/config.json`. Mobilewright never sends personal information or test data. The Scarf pixel is a plain HTTP request, so Scarf receives the usual request metadata (source IP, user agent); Scarf states it does not retain raw IP addresses. Setting `MOBILEWRIGHT_DISABLE_TELEMETRY` (any value) or `DO_NOT_TRACK` (any value except `0` or `false`) opts out of both. +For Mobilewright MCP, set `MOBILEMCP_DISABLE_TELEMETRY=1` in the MCP server's environment. See [MCP telemetry configuration](https://github.com/mobile-next/mobile-mcp#telemetry) for the client configuration example. + ## Contributing -```bash -# Run the repository's own unit tests -npm test -``` +See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, reporting issues, and submitting changes. ## Framework Support