### Install Dependencies and Build Project Source: https://github.com/mobile-next/mobilewright/blob/main/CONTRIBUTING.md Clone the repository, install npm dependencies, and build the project. This is a standard setup for Node.js projects within an npm workspace. ```bash git clone https://github.com/mobile-next/mobilewright.git cd mobilewright npm install npm run build ``` -------------------------------- ### Full Mobilewright Configuration Example Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/timeouts.md A comprehensive example demonstrating the configuration of various timeouts including test, global, action, app launch, install, allocation, and upload timeouts. ```typescript // mobilewright.config.ts import { defineConfig } from 'mobilewright'; export default defineConfig({ timeout: 60_000, globalTimeout: 30 * 60_000, use: { actionTimeout: 10_000, appLaunchTimeout: 45_000, installTimeout: 3 * 60_000, }, expect: { timeout: 10_000, }, driver: { type: 'mobilenext', apiKey: process.env.MOBILENEXT_API_KEY, allocationTimeout: 15 * 60_000, uploadTimeout: 2 * 60_000, testResult: { uploadReport: 'on-failure' }, }, }); ``` -------------------------------- ### Install Checkly Reporter Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/integrations/checkly.md Install the Checkly reporter package using npm. ```bash npm install --save-dev @checkly/playwright-reporter ``` -------------------------------- ### Install Datadog CI Tool Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/integrations/datadog.md Install the Datadog CI tool as a development dependency. ```bash npm install --save-dev @datadog/datadog-ci ``` -------------------------------- ### GitHub Actions Sharding Example Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/sharding.md Example GitHub Actions workflow demonstrating how to set up sharding using a matrix strategy for jobs. It includes running tests on each shard and uploading artifact reports. ```yaml jobs: test: strategy: matrix: shard: [1, 2, 3] steps: - uses: actions/checkout@v5 - run: npx mobilewright test --shard=${{ matrix.shard }}/3 - uses: actions/upload-artifact@v5 with: name: blob-report-${{ matrix.shard }} path: blob-report/ merge-reports: needs: test steps: - uses: actions/download-artifact@v5 with: path: all-blob-reports pattern: blob-report-* merge-multiple: true - run: npx mobilewright merge-reports --reporter html ./all-blob-reports - uses: actions/upload-artifact@v5 with: name: html-report path: playwright-report/ ``` -------------------------------- ### Install Mobilewright Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Install the mobilewright package using npm. ```bash npm install mobilewright ``` -------------------------------- ### CI Example for GitHub Actions Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/integrations/checkly.md Example configuration for running Mobilewright tests with Checkly integration in a GitHub Actions workflow. ```yaml - name: Run Mobilewright tests env: CHECKLY_API_KEY: ${{ secrets.CHECKLY_API_KEY }} CHECKLY_ACCOUNT_ID: ${{ secrets.CHECKLY_ACCOUNT_ID }} run: npx mobilewright test ``` -------------------------------- ### Screen Action Examples Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Execute actions that affect the entire screen or app navigation. ```javascript swipe(), pressButton(), goBack(), screenshot() ``` -------------------------------- ### Install Mobilewright Package Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md Install the core Mobilewright package and the test runner using npm. ```bash npm install mobilewright @mobilewright/test ``` -------------------------------- ### Locator API Examples Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Interact with UI elements using various locator strategies provided by the framework. ```javascript getByText(), getByRole(), getByTestId(), getByLabel(), first(), nth(), count() ``` -------------------------------- ### Set Install Timeout in Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/timeouts.md Configure the timeout for app installation when using the installApps option. This is relevant for slow installations over USB or on cloud devices. ```typescript export default defineConfig({ use: { installTimeout: 3 * 60_000, // 3 minutes }, }); ``` -------------------------------- ### Initialize Mobilewright Project Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md Initialize a new Mobilewright project to create configuration files and example tests. ```bash npm init mobilewright@latest ``` -------------------------------- ### Multi-Project Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Define configurations for multiple projects within a single test setup. ```javascript projects: [{ name: 'iPhone', use: { platform: 'ios' } }, ...] ``` -------------------------------- ### Device Lifecycle and Controls Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Manages device orientation, opens URLs or deep links, and controls application lifecycle (launch, terminate, install, uninstall). Also lists installed apps and retrieves the foreground app. ```typescript // Orientation await device.setOrientation('landscape'); const orientation = await device.getOrientation(); // URLs / deep links (goto is a Playwright-style alias for openUrl) await device.goto('myapp://settings'); await device.openUrl('https://example.com'); // App lifecycle await device.launchApp('com.example.app', { locale: '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'); // Cleanup (disconnects + stops auto-started mobilecli) await device.close(); ``` -------------------------------- ### Mobilewright Configuration Example Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md Configure your Mobilewright project by specifying the target platform, app details, and device. ```typescript import { defineConfig } from 'mobilewright'; export default defineConfig({ platform: 'ios', bundleId: 'com.example.myapp', deviceName: /iPhone 16/, installApps: './builds/myapp.ipa', timeout: 10_000, }); ``` -------------------------------- ### Locator Assertion Examples Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Verify the state and properties of located elements. ```javascript toBeVisible(), toBeEnabled(), toBeChecked(), toBeHidden(), toHaveText(), toHaveValue() ``` -------------------------------- ### GitHub Actions CI Example for Datadog Upload Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/integrations/datadog.md Example workflow for GitHub Actions to run Mobilewright tests and upload results to Datadog. The 'if: always()' ensures upload even if tests fail. ```yaml - name: Run Mobilewright tests run: npx mobilewright test - name: Upload results to Datadog if: always() env: DD_API_KEY: ${{ secrets.DD_API_KEY }} run: | npx datadog-ci junit upload \ --service my-app-ios-tests \ --tags platform:ios \ test-results.xml ``` -------------------------------- ### Value Assertion Examples Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Assert on general values and data structures. ```javascript toBe(), toEqual(), toContain(), toBeGreaterThan(), toMatch() ``` -------------------------------- ### Example Mobilewright Test Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md A starter test case to verify that the application launches and displays the home screen with expected text. ```typescript import { test, expect } from '@mobilewright/test'; test('app launches and shows home screen', async ({ screen }) => { await expect(screen.getByText('Welcome')).toBeVisible(); }); ``` -------------------------------- ### Define iOS and Android Projects Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/projects.md Configure multiple projects, each targeting a specific platform (iOS or Android) with its own app installation path. This allows running the same test suite on different platforms from a single configuration. ```typescript import { defineConfig } from 'mobilewright'; export default defineConfig({ testDir: '.', timeout: 120_000, bundleId: 'com.example.myapp', workers: 2, projects: [ { name: 'ios', use: { platform: 'ios', installApps: 'ios/MyApp.zip', }, }, { name: 'android', use: { platform: 'android', installApps: 'android/MyApp.apk', }, }, ], }); ``` -------------------------------- ### Filling Text Fields Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Automates the process of entering text into input fields. This example shows how to fill email and password fields. ```typescript await screen.getByLabel('Email').fill('user@example.com'); await screen.getByLabel('Password').fill('secret'); ``` -------------------------------- ### Playwright Web Assertion Examples Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/webviews.md Provides examples of Playwright's web-first assertions for verifying element visibility, text content, attribute values, counts, classes, URLs, and titles. These assertions retry until the condition is met or a timeout occurs. ```typescript await expect(page.locator('#status')).toBeVisible(); await expect(page.getByRole('heading')).toHaveText('Dashboard'); await expect(page.locator('input[name="email"]')).toHaveValue(/@example\.com$/); await expect(page.getByRole('listitem')).toHaveCount(3); await expect(page.locator('#btn')).toHaveClass(/primary/); await expect(page).toHaveURL(///dashboard/); await expect(page).toHaveTitle(/Dashboard/); ``` -------------------------------- ### Playwright Web Navigation Examples Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/webviews.md Shows common Playwright navigation methods for web pages, such as going to a URL, reloading, navigating back/forward, and waiting for specific load states or URLs. ```typescript // Navigation await page.goto('https://example.com/login'); await page.reload(); await page.goBack(); await page.goForward(); await page.waitForLoadState('domcontentloaded'); await page.waitForURL(///dashboard/); const title = await page.title(); const html = await page.content(); const ua = await page.evaluate(() => navigator.userAgent); ``` -------------------------------- ### Tapping Elements Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Simulates user interactions by tapping on elements. Includes examples for a single tap, double tap, and long press. ```typescript await screen.getByText('Sign In').tap(); await screen.getByRole('button', { name: 'Submit' }).doubleTap(); await screen.getByText('Options').longPress(); ``` -------------------------------- ### Mobilewright Test Fixture Example Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Use `test` and `expect` from `@mobilewright/test` for mobile-specific testing. Configure app bundle and video recording with `test.use`. ```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('Password').fill('password123'); await screen.getByRole('button', { name: 'Sign In' }).tap(); await expect(screen.getByText('Welcome back')).toBeVisible(); }); ``` -------------------------------- ### Run Mobilewright Doctor Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/troubleshooting.md Use `mobilewright doctor` to check your system's compatibility and setup for mobile testing. Run this command first when encountering issues. ```bash npx mobilewright doctor ``` -------------------------------- ### Finding Elements by Accessibility Label Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Finds an element using its accessibility label, which is crucial for users with disabilities and for robust testing. This example targets the 'Username' field. ```typescript screen.getByLabel('Username'); ``` -------------------------------- ### Playwright Web Locator Examples Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/webviews.md Demonstrates various Playwright locator strategies for finding elements within a web view, including by ID, role, text, label, placeholder, test ID, alt text, and title. ```typescript // Locators — same builders as Playwright page.locator('#submit'); page.getByRole('button', { name: 'Sign in' }); page.getByText('Welcome back'); page.getByLabel('Email'); page.getByPlaceholder('you@example.com'); page.getByTestId('cart'); page.getByAltText('Company logo'); page.getByTitle('Close'); ``` -------------------------------- ### GitHub Actions Workflow for Mobilewright Tests Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/ci.md This YAML configuration sets up a GitHub Actions workflow to run Mobilewright tests on pushes and pull requests to the main branch. It checks out code, sets up Node.js, installs dependencies, runs tests, and uploads the HTML report as an artifact. ```yaml name: Mobilewright Tests on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: macos-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - run: npm ci - run: npx mobilewright test --reporter html - uses: actions/upload-artifact@v4 if: ${{ !cancelled() }} with: name: mobilewright-report path: mobilewright-report/ retention-days: 30 ``` -------------------------------- ### Grouping Tests with `test.describe` Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Organizes related tests into logical groups using `test.describe`. This improves test suite readability and maintainability. Includes examples for a login flow. ```typescript import { test, expect } from '@mobilewright/test'; test.describe('login flow', () => { test('shows login form', async ({ screen }) => { await expect(screen.getByLabel('Email')).toBeVisible(); await expect(screen.getByLabel('Password')).toBeVisible(); }); test('rejects invalid credentials', async ({ screen }) => { await screen.getByLabel('Email').fill('bad@example.com'); await screen.getByLabel('Password').fill('wrong'); await screen.getByRole('button', { name: 'Sign In' }).tap(); await expect(screen.getByText('Invalid credentials')).toBeVisible(); }); }); ``` -------------------------------- ### AI Agent Controlling a Real Phone Source: https://github.com/mobile-next/mobilewright/blob/main/README.md An AI agent can control a real phone using semantic actions by interacting with the accessibility tree. This example shows tapping a button, filling an email field, and asserting visibility. ```typescript await screen.getByRole('button', { name: 'Sign In' }).tap(); await screen.getByLabel('Email').fill('user@example.com'); await expect(screen.getByText('Welcome')).toBeVisible(); ``` -------------------------------- ### Initialize Mobilewright Project Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Scaffold `mobilewright.config.ts` and `example.test.ts` using `npx mobilewright init`. ```bash npx mobilewright init ``` -------------------------------- ### Launch iOS Device and Automate Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Launches an iOS simulator, fills in login credentials, taps the sign-in button, asserts a welcome message, takes a screenshot, and closes the device. Requires Node.js >= 18 and a booted iOS simulator. ```typescript import { ios, expect } from 'mobilewright'; const device = await ios.launch({ bundleId: 'com.example.myapp' }); const { screen } = device; 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(); const screenshot = await screen.screenshot(); await device.close(); ``` -------------------------------- ### List Connected Devices Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Display a list of all available devices, simulators, and emulators connected to your system. This helps in identifying target devices for testing. ```bash npx mobilewright devices ``` -------------------------------- ### Specify Platform in Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Configure the target platform for your tests by setting the 'platform' option in your configuration file. ```javascript platform: 'ios' or 'android' ``` -------------------------------- ### Run Docker Tests with Cloud Devices Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Run tests using the Mobile Wright Docker container, connecting to cloud devices. Mount your project and pass the API key using the `-e` flag to authenticate with Mobile Next Cloud. ```bash docker run --rm \ -v "$(pwd):/home/mwuser" \ -e MOBILENEXT_API_KEY="$MOBILENEXT_API_KEY" \ ghcr.io/mobile-next/mobilewright test ``` -------------------------------- ### Basic Sharding Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/sharding.md Configure sharding by specifying the current shard number and the total number of shards using `--shard x/n`. This command should be run on each machine participating in the sharding. ```bash # On each Mac (replace N with the shard number) npx mobilewright test --shard=N/3 --workers=4 ``` -------------------------------- ### Run Single Test File Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Execute a specific test file. Provide the relative or absolute path to the test file. ```bash npx mobilewright test tests/login.test.ts ``` -------------------------------- ### Attach to and Navigate In-App Web View Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/webviews.md Launches an app, navigates to a screen with a web view, attaches to it using `screen.getByWebView()`, and then navigates to a URL within that web view. Asserts the presence of an element and its text. ```typescript import { test, expect } from '@mobilewright/test'; test('open the in-app browser', async ({ device, screen }) => { await device.launchApp('com.example.app'); // Navigate to the screen that hosts the web view (app-specific): await screen.getByText('Web View').tap(); // Attach to the web view and get a Playwright-style Page: const page = await screen.getByWebView().page(); await page.goto('https://example.com'); await expect(page.getByRole('heading')).toHaveText('Example Domain'); }); ``` -------------------------------- ### Launchers (ios and android) Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Provides entry points for launching iOS and Android devices, similar to Playwright's browser contexts. Supports auto-discovery, specific app launching, targeting simulators by name or UDID, and listing available devices. ```APIDOC ## Launchers — `ios` and `android` ### Description The top-level entry points for launching and managing mobile devices. These mirror Playwright's browser contexts. ### Methods - `ios.launch(options?: LaunchOptions)`: Launches an iOS device. - `android.launch(options?: LaunchOptions)`: Launches an Android device. - `ios.devices()`: Lists available iOS devices. - `android.devices()`: Lists available Android devices. ### Options for `launch()` - `bundleId` (string): The bundle ID of the app to launch. - `deviceName` (RegExp | string): Targets a specific simulator by name. - `deviceId` (string): Explicit device UDID to connect to, skipping discovery. ### Example ```typescript import { ios, android } from 'mobilewright'; // Launch with auto-discovery 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/ }); // Explicit device UDID const device = await ios.launch({ deviceId: '5A5FCFCA-...' }); // List available devices const devices = ios.devices(); ``` ``` -------------------------------- ### Run Repository Unit Tests Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Execute the repository's own unit tests using npm. ```bash # Run the repository's own unit tests npm test ``` -------------------------------- ### Run a Single Project Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/projects.md Execute tests for a specific project using the `--project` flag. This is useful for targeting a single platform or configuration during development or debugging. ```bash npx mobilewright test --project=android ``` -------------------------------- ### Set Test Timeout in Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/timeouts.md Configure the default timeout for a single test in the mobilewright.config.ts file. This includes fixture setup, test body, and hooks. ```typescript export default defineConfig({ timeout: 60_000, // 60 seconds }); ``` -------------------------------- ### Per-Project Overrides in Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/projects.md Demonstrates how project-level `use` options can override top-level configuration defaults. This is common for specifying platform-specific settings like `platform` and `installApps` while sharing common settings like `bundleId` and `timeout`. ```typescript export default defineConfig({ bundleId: 'com.example.myapp', timeout: 120_000, projects: [ { name: 'ios', use: { platform: 'ios', installApps: 'ios/MyApp.zip', }, }, { name: 'android', use: { platform: 'android', installApps: 'android/MyApp.apk', }, }, ], }); ``` -------------------------------- ### Launch iOS and Android Devices Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Launches iOS and Android devices with various options for app targeting and device selection. Use auto-discovery for simulators or specify device IDs for direct connections. ```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/ }); // Explicit device UDID (skips discovery) const device = await ios.launch({ deviceId: '5A5FCFCA-...' }); // List available devices const devices = ios.devices(); const devices = android.devices(); ``` -------------------------------- ### Run Project Tests Source: https://github.com/mobile-next/mobilewright/blob/main/CONTRIBUTING.md Execute the project's test suite locally to ensure code quality and functionality. Coverage reports can also be generated. ```bash # run the tests npm test # or for coverage reports npm test:coverage ``` -------------------------------- ### Get Machine-Readable Doctor Output Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/troubleshooting.md Obtain JSON output from `mobilewright doctor` for easier parsing in CI/CD pipelines or by AI agents. This provides structured diagnostic information. ```bash # JSON output (useful for CI or AI agents) npx mobilewright doctor --json ``` -------------------------------- ### Chaining Locators for Nested Elements Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Narrows down the search for an element by first locating a parent element and then searching within it. This example finds a 'Delete' button within a specific 'Cell'. ```typescript const row = screen.getByType('Cell').first(); await row.getByRole('button', { name: 'Delete' }).tap(); ``` -------------------------------- ### Extend Test Timeout in beforeEach Hook Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/timeouts.md Dynamically extend the current test timeout within a beforeEach hook. This is useful for scenarios where setup might take longer than the default. ```typescript test.beforeEach(async ({}, testInfo) => { testInfo.setTimeout(testInfo.timeout + 30_000); }); ``` -------------------------------- ### Run Docker Tests on Linux Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Mount your project directory into the MobileWright Docker container and run tests on Linux. This command includes the `--add-host` flag for Linux-specific networking and maps your current directory to `/home/mwuser`. ```bash docker run --rm \ --add-host=host.docker.internal:host-gateway \ -v "$(pwd):/home/mwuser" \ ghcr.io/mobile-next/mobilewright test ``` -------------------------------- ### Element Assertions Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Verifies the state of UI elements using `expect`. Assertions automatically handle waiting and retries. Examples include checking visibility, enabled state, and text content. ```typescript await expect(screen.getByText('Welcome')).toBeVisible(); await expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled(); await expect(screen.getByTestId('greeting')).toHaveText('Hello, World'); ``` -------------------------------- ### Basic Screen Interaction Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/fixtures.md Use the 'screen' fixture to interact with elements on the device screen. It is scoped to each test and handles video recording and screenshots on failure. ```typescript import { test, expect } from '@mobilewright/test'; test('shows welcome message', async ({ screen }) => { await expect(screen.getByText('Welcome')).toBeVisible(); }); ``` -------------------------------- ### Run Tests from Specific Project Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Execute tests belonging to a particular project configuration. Specify the project name using the --project flag. ```bash npx mobilewright test --project=ios ``` -------------------------------- ### Running Individual Shards Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/sharding.md Execute a specific shard of the test suite on each machine. Replace `x/n` with the appropriate shard identifier for each machine. ```bash # Machine 1 npx mobilewright test --shard=1/3 # Machine 2 npx mobilewright test --shard=2/3 # Machine 3 npx mobilewright test --shard=3/3 ``` -------------------------------- ### Reporter Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Specify test reporters using the configuration file or command-line arguments. ```bash list, html, json, blob — via config or --reporter ``` -------------------------------- ### Serve Report on Custom Host and Port Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Change the host and port where the HTML test report is served. Allows access from different network interfaces or avoids port conflicts. ```bash npx mobilewright show-report --host 0.0.0.0 --port 8080 ``` -------------------------------- ### Device Control Functions Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Manage device settings and state. ```javascript setOrientation(), openUrl(), listApps(), getForegroundApp() ``` -------------------------------- ### Screen Source: https://github.com/mobile-next/mobilewright/blob/main/README.md The entry point for finding and interacting with UI elements on the device screen. Accessed via `device.screen`. ```APIDOC ## Screen ### Description Entry point for finding and interacting with elements on the device screen. Accessed via `device.screen`. ### Locator Factories - `screen.getByLabel(text: string | RegExp)`: Finds elements by accessibility label. - `screen.getByTestId(id: string)`: Finds elements by accessibility identifier. - `screen.getByText(text: string | RegExp, options?: { exact?: boolean })`: Finds elements by visible text. - `screen.getByType(type: string)`: Finds elements by their type (e.g., 'TextField'). - `screen.getByRole(role: string, options?: { name?: string })`: Finds elements by semantic role and name. - `screen.getByPlaceholder(text: string)`: Finds elements by placeholder text. ### Direct Actions - `screen.screenshot(options?: ScreenshotOptions)`: Captures a screenshot of the screen. - `screen.swipe(direction: SwipeDirection, options?: SwipeOptions)`: Performs a swipe gesture on the screen. - `screen.pressButton(button: ButtonType)`: Presses a system button (e.g., 'HOME'). - `screen.tap(x: number, y: number)`: Performs a tap at raw coordinates. ### Screenshot Options - `format` ('png' | 'jpeg'): The image format. - `quality` (number): The quality for JPEG format (0-100). ### Swipe Options - `distance` (number): The distance to swipe in pixels. - `duration` (number): The duration of the swipe in milliseconds. ### Example ```typescript // Find an element by its accessibility label const emailInput = screen.getByLabel('Email'); // Take a screenshot await screen.screenshot(); await screen.screenshot({ format: 'jpeg', quality: 80 }); // Swipe up await screen.swipe('up'); await screen.swipe('down', { distance: 300, duration: 500 }); ``` ``` -------------------------------- ### Enable Mobilewright Logs on Windows (Command Prompt) Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/troubleshooting.md Use the Command Prompt on Windows to set the `DEBUG` environment variable. This allows you to capture detailed logs for Mobilewright operations. ```cmd :: Command Prompt set DEBUG=mw:* npx mobilewright test ``` -------------------------------- ### Use the screenshot buffer Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/screenshots.md Demonstrates accessing the returned Buffer directly for further processing. ```typescript const buffer = await screen.screenshot(); console.log(`Screenshot size: ${buffer.length} bytes`); ``` -------------------------------- ### Set Checkly Credentials Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/integrations/checkly.md Set the Checkly API key and account ID as environment variables before running tests. ```bash export CHECKLY_API_KEY= export CHECKLY_ACCOUNT_ID= ``` -------------------------------- ### Run Tests and Upload to Datadog Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/integrations/datadog.md Execute Mobilewright tests and then upload the generated JUnit report to Datadog using the datadog-ci tool. Ensure your DD_API_KEY is set. ```bash npx mobilewright test DD_API_KEY= \ npx datadog-ci junit upload \ --service my-app-ios-tests \ --tags platform:ios \ test-results.xml ``` -------------------------------- ### Open Specific Test Report Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Serve an HTML test report from a specified directory. Useful for viewing historical or specific test run reports. ```bash npx mobilewright show-report ./my-report ``` -------------------------------- ### Run Docker Tests on macOS/Windows Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Mount your project directory into the MobileWright Docker container and run tests on macOS or Windows. The `-v` flag maps your current directory to `/home/mwuser` inside the container. ```bash docker run --rm \ -v "$(pwd):/home/mwuser" \ ghcr.io/mobile-next/mobilewright test ``` -------------------------------- ### Run Mobilewright Tests Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md Execute the Mobilewright test suite using the command line interface. ```bash npx mobilewright test ``` -------------------------------- ### App Lifecycle Management Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Control the lifecycle of the application under test. ```javascript launchApp(), terminateApp(), installApp(), uninstallApp() ``` -------------------------------- ### Capture Screenshot Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/screenshots.md Captures the current device screen and returns the image data as a Buffer. ```APIDOC ## POST /screen/screenshot ### Description Captures the current device screen and returns the image data as a Buffer. ### Method POST ### Endpoint /screen/screenshot ### Parameters #### Request Body - **options** (object) - Optional - Options for capturing the screenshot. - **path** (string) - Optional - File path to save the screenshot to. The directory will be created automatically if it doesn't exist. - **format** (string) - Optional - Image format. Defaults to 'png'. Allowed values: 'png' | 'jpeg'. - **quality** (number) - Optional - JPEG quality (0-100). Only applies when format is 'jpeg'. ### Request Example ```json { "options": { "path": "screenshot.png" } } ``` ### Response #### Success Response (200) - **buffer** (Buffer) - The image data of the screenshot. #### Response Example ```json { "buffer": "" } ``` ``` -------------------------------- ### Using the `device` Fixture for Deep Linking Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Leverages the `device` fixture for actions beyond screen interaction, such as opening deep links. This test verifies that a specific URL opens the expected screen. ```typescript import { test, expect } from '@mobilewright/test'; test('deep link opens profile', async ({ device, screen }) => { await device.openUrl('myapp://profile/123'); await expect(screen.getByText('Profile')).toBeVisible(); }); ``` -------------------------------- ### Capture Screenshot Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Take a screenshot of the current screen on the active device or simulator. The screenshot is saved to a default location. ```bash npx mobilewright screenshot ``` -------------------------------- ### Negation and Timeouts Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/assertions.md Demonstrates how to negate assertions and override default timeouts for specific assertions. ```APIDOC ## Negation Add `.not` before any assertion to negate it: ```typescript await expect(screen.getByText('Error')).not.toBeVisible(); await expect(screen.getByRole('button')).not.toBeDisabled(); await expect(screen.getByTestId('title')).not.toHaveText('Loading'); ``` ## Timeouts Override the default timeout for a single assertion: ```typescript await expect(screen.getByText('Done')).toBeVisible({ timeout: 10_000 }); ``` ``` -------------------------------- ### Set App Launch Timeout in Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/timeouts.md Configure the timeout for waiting for an application to launch and reach the foreground. This is particularly useful for real devices which may have slower app launch times. ```typescript export default defineConfig({ use: { appLaunchTimeout: 60_000, // 60 seconds for slow real devices }, }); ``` -------------------------------- ### Pressing Hardware Buttons Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Simulates pressing native hardware buttons. Supports 'HOME' and 'BACK' (Android only). ```typescript await screen.pressButton('HOME'); await screen.pressButton('BACK'); // android only ``` -------------------------------- ### Target Specific Device for Screenshot Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Capture a screenshot from a particular device by specifying its ID. Use the -d flag followed by the device ID. ```bash npx mobilewright screenshot -d ``` -------------------------------- ### Capture a screenshot Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/screenshots.md Captures the current device screen and returns the image data as a Buffer. ```typescript const buffer = await screen.screenshot(); ``` -------------------------------- ### Device Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Manages the connection lifecycle and provides device/app-level controls, including orientation, URL handling, app lifecycle, and cleanup. ```APIDOC ## Device ### Description Manages the connection lifecycle and exposes device and app-level controls. ### Methods - `device.setOrientation(orientation: 'portrait' | 'landscape')`: Sets the device orientation. - `device.getOrientation()`: Gets the current device orientation. - `device.goto(url: string)`: Navigates to a URL (alias for `openUrl`). - `device.openUrl(url: string)`: Opens a URL or deep link on the device. - `device.launchApp(bundleId: string, options?: { locale?: string, noWaitAfter?: boolean })`: Launches an application and waits for it to be in the foreground. - `device.terminateApp(bundleId: string)`: Terminates a running application. - `device.listApps()`: Lists all installed applications on the device. - `device.getForegroundApp()`: Gets the bundle ID of the currently foreground application. - `device.installApp(appPath: string)`: Installs an application from a given path. - `device.uninstallApp(bundleId: string)`: Uninstalls an application. - `device.close()`: Cleans up the connection and stops any auto-started servers. ### Example ```typescript // Set orientation to landscape await device.setOrientation('landscape'); // Open a URL await device.openUrl('https://example.com'); // Launch an app and wait for foreground await device.launchApp('com.example.app', { locale: 'fr_FR' }); // List installed apps const apps = await device.listApps(); // Close the connection await device.close(); ``` ``` -------------------------------- ### Configure Test Reporters Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/running-tests.md Specify the reporter to use for test output. Options include 'list' (default), 'html', 'json', and 'junit'. The 'html' reporter generates an interactive report. ```bash # Terminal list output (default) npx mobilewright test --reporter list ``` ```bash # Interactive HTML report npx mobilewright test --reporter html npx mobilewright show-report ``` -------------------------------- ### Touch Interaction Methods Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Perform common touch gestures on UI elements. ```javascript tap(), doubleTap(), longPress(), fill(), scrollIntoViewIfNeeded() ``` -------------------------------- ### Viewing Mobilewright Report Locally Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/ci.md After downloading the report artifact from GitHub Actions, use this command to open and view the Mobilewright test report on your local machine. ```bash npx mobilewright show-report ./path/to/downloaded/mobilewright-report ``` -------------------------------- ### Capture Screenshot with Docker on Linux Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Capture a screenshot using the MobileWright Docker container on Linux. This command includes the `--add-host` flag for Linux-specific networking and maps your project directory to `/home/mwuser`. ```bash docker run --rm \ --add-host=host.docker.internal:host-gateway \ -v "$(pwd):/home/mwuser" \ ghcr.io/mobile-next/mobilewright screenshot ``` -------------------------------- ### Run Mobilewright Tests with HTML Reporter Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md Execute tests and generate an HTML report for detailed analysis of test results. ```bash npx mobilewright test --reporter html ``` -------------------------------- ### Run Specific Test File or Directory Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/running-tests.md Filter test execution to a single file or a directory. This is useful for focusing on a specific part of your test suite. ```bash npx mobilewright test tests/login.test.ts ``` ```bash npx mobilewright test tests/checkout/ ``` -------------------------------- ### Parallel Workers and Sharding Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Configure parallel test execution and sharding for faster test runs. ```bash --workers 4, --shard 1/3, fullyParallel: true ``` -------------------------------- ### Mobilewright Configuration Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Configure platform, bundle ID, device name, and timeouts in `mobilewright.config.ts`. ```typescript import { defineConfig } from 'mobilewright'; export default defineConfig({ platform: 'ios', bundleId: 'com.example.myapp', deviceName: 'iPhone 16', timeout: 10_000, }); ``` -------------------------------- ### Running Tests with Workers Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/sharding.md Use the `--workers` option to parallelize tests on a single machine. This is suitable for remote devices where the bottleneck is not the machine's CPU or memory. ```bash npx mobilewright test --workers=20 ``` -------------------------------- ### Basic Assertions with expect Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Use `expect` to make assertions on locators. Supports negation with `.not` and custom timeouts. ```typescript import { expect } from 'mobilewright'; await expect(locator).toBeVisible(); await expect(locator).not.toBeVisible(); await expect(locator).toBeEnabled(); await expect(locator).not.toBeEnabled(); await expect(locator).toHaveText('Welcome back!'); await expect(locator).toHaveText(/welcome/i); await expect(locator).toContainText('back'); await expect(locator).toBeVisible({ timeout: 10_000 }); ``` -------------------------------- ### Show Mobilewright HTML Test Report Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/intro.md Serve the generated HTML test report locally to view interactive test results, errors, and screenshots. ```bash npx mobilewright show-report ``` -------------------------------- ### Finding Elements by Text Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/writing-tests.md Locates an element that displays the exact text 'Sign In'. This is a common method for finding buttons or labels. ```typescript screen.getByText('Sign In'); ``` -------------------------------- ### Configure MobileWright for Cloud Devices Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Configure your `mobilewright.config.ts` file to use the Mobile Next Cloud driver. The API key should be read from an environment variable for security. ```typescript import { defineConfig } from 'mobilewright'; export default defineConfig({ platform: 'ios', // or 'android' driver: { type: 'mobilenext', apiKey: process.env.MOBILENEXT_API_KEY, }, }); ``` -------------------------------- ### Run Tests Matching Title Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Execute tests whose titles match a given regular expression. Useful for running a subset of tests based on their names. ```bash npx mobilewright test --grep "sign in" ``` -------------------------------- ### Select Specific Web View by Index Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/webviews.md Attaches to a specific web view within the current screen when multiple web views are present, using its index. ```typescript const page = await screen.getByWebView().nth(1).page(); ``` -------------------------------- ### Capture Screenshot with Docker on macOS/Windows Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Capture a screenshot using the MobileWright Docker container on macOS or Windows. Mount your project directory to save the output file to your host machine. ```bash docker run --rm \ -v "$(pwd):/home/mwuser" \ ghcr.io/mobile-next/mobilewright screenshot # → screenshot.png appears in the current directory ``` -------------------------------- ### Playwright Web Actions and Auto-Waiting Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/webviews.md Illustrates common Playwright actions on web locators, such as filling input fields, clicking buttons, pressing keys, hovering, and scrolling. These actions automatically wait for elements to be ready. ```typescript await page.getByPlaceholder('Email').fill('user@example.com'); await page.getByRole('button', { name: 'Sign in' }).click(); await page.locator('#search').press('Enter'); await page.getByText('Terms').hover(); await page.locator('#footer-link').scrollIntoViewIfNeeded(); const count = await page.getByRole('listitem').count(); const value = await page.locator('#email').inputValue(); ``` -------------------------------- ### Test Framework Utilities Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Utilize built-in test framework functions for managing test execution flow and organization. ```javascript test.skip(), test.step(), test.beforeEach(), test.describe.serial() ``` -------------------------------- ### Save Screenshot to Specific File Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/cli.md Capture a screenshot and save it to a specified file path. Use the -o flag followed by the desired filename. ```bash npx mobilewright screenshot -o home-screen.png ``` -------------------------------- ### Show Mobilewright HTML Report Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Open the HTML report generated by the `--reporter html` option. You can specify a directory to open the report from. ```bash npx mobilewright show-report ``` ```bash npx mobilewright show-report mobilewright-report/ ``` -------------------------------- ### Enable Per-File Parallelism Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/parallelism.md For parallel execution of tests within a single file without enabling `fullyParallel` globally, add `test.describe.configure({ mode: 'parallel' });` at the top of the test file. ```typescript import { test } from '@mobilewright/test'; test.describe.configure({ mode: 'parallel' }); ``` -------------------------------- ### Pass Environment Variables Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/getting-started/running-tests.md Set environment variables that will be accessible to both the test runner and your test code. This is useful for configuring test environments. ```bash TEST_USER=value npx mobilewright test ``` -------------------------------- ### Screen Direct Actions Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Performs direct actions on the screen such as taking screenshots, swiping, pressing the home button, or tapping at raw coordinates. Supports custom screenshot formats and quality. ```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 ``` -------------------------------- ### Mobilewright CLI Commands Source: https://github.com/mobile-next/mobilewright/blob/main/ROADMAP.md Common commands for interacting with the Mobilewright command-line interface. ```bash test, show-report, init, devices, doctor, screenshot ``` -------------------------------- ### Specify Screenshot Output File Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/docker.md Capture a screenshot using the MobileWright Docker container and specify a custom output filename using the `--output` flag. The path is relative to the working directory inside the container. ```bash docker run --rm \ -v "$(pwd):/home/mwuser" \ ghcr.io/mobile-next/mobilewright screenshot --output before-login.png ``` -------------------------------- ### Save screenshot to file Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/screenshots.md Saves the captured screenshot to a specified path. The directory is created automatically if it does not exist. ```typescript const buffer = await screen.screenshot({ path: 'screenshot.png' }); ``` -------------------------------- ### Enable Mobilewright Logs on Windows (PowerShell) Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/troubleshooting.md On Windows, use PowerShell to set the `DEBUG` environment variable before running Mobilewright commands. This enables detailed logging for troubleshooting. ```powershell # PowerShell $env:DEBUG = "mw:*" npx mobilewright test ``` -------------------------------- ### Locator Actions Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Performs actions on a located element, including tapping, filling text, swiping, and scrolling into view. Actions automatically wait for the element to be visible, enabled, and stable. ```typescript await locator.tap() await locator.doubleTap() await locator.longPress({ duration: 1000 }) await locator.fill('hello@example.com') // tap to focus + type text await locator.swipe({ direction: 'left' }) await locator.scrollIntoViewIfNeeded() ``` -------------------------------- ### Save Screenshot to File Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/guides/screenshots.md Captures a screenshot and saves it directly to a specified file path with optional format and quality settings. ```APIDOC ## POST /screen/screenshot (with path option) ### Description Captures the current device screen and saves it to a file. The directory will be created automatically if it doesn't exist. The image data is still returned as a Buffer. ### Method POST ### Endpoint /screen/screenshot ### Parameters #### Request Body - **options** (object) - Required - Options for capturing and saving the screenshot. - **path** (string) - Required - File path to save the screenshot to. - **format** (string) - Optional - Image format. Defaults to 'png'. Allowed values: 'png' | 'jpeg'. - **quality** (number) - Optional - JPEG quality (0-100). Only applies when format is 'jpeg'. ### Request Example ```json { "options": { "path": "screenshots/home.jpg", "format": "jpeg", "quality": 80 } } ``` ### Response #### Success Response (200) - **buffer** (Buffer) - The image data of the screenshot. #### Response Example ```json { "buffer": "" } ``` ``` -------------------------------- ### Screen Locator Factories Source: https://github.com/mobile-next/mobilewright/blob/main/README.md Provides various methods to locate elements on the screen using accessibility labels, IDs, text, roles, and placeholders. Supports exact text matches, regex, and substring matching. ```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 ``` -------------------------------- ### Combining Sharding and Workers Source: https://github.com/mobile-next/mobilewright/blob/main/docs/src/test/sharding.md Combine sharding with the `--workers` option to run multiple tests in parallel within each shard on its respective machine. ```bash npx mobilewright test --shard=1/3 --workers=2 ```