# WebdriverIO v10 documentation: Platforms > 60 pages. Index of all sections: https://webdriver.io/llms.txt --- Source: https://webdriver.io/docs/platforms/web.md # Web Browsers WebdriverIO automates desktop browsers (Chrome, Chromium, Firefox, Microsoft Edge and Safari) through standard browser drivers. By default it tries to open a [WebDriver BiDi](/docs/automationProtocols.md) session, the bi-directional successor of the classic WebDriver protocol. BiDi powers features such as network mocking and Web API emulation. Set `wdio:enforceWebDriverClassic: true` in your capabilities to opt out. You don't need to install drivers yourself: set a `browserName` and WebdriverIO downloads and starts the matching Chromedriver, Geckodriver or Edgedriver. It also installs Chrome, Chromium or Firefox when no local installation is found. Microsoft Edge must already be installed, and Safaridriver ships with macOS. The same testrunner can also run tests inside the browser with the Browser Runner. This covers unit and component tests for React, Vue, Svelte, SolidJS, Preact, Lit and Stencil. ## Quick start[​](#quick-start "Direct link to Quick start") Scaffold a project interactively with `npm init wdio@latest .`. Passing `--yes` picks the defaults: Mocha, Chrome and page objects. To set a project up by hand, install the testrunner, a framework adapter, a reporter and `tsx` for TypeScript: ``` npm install --save-dev @wdio/cli @wdio/local-runner @wdio/mocha-framework @wdio/spec-reporter tsx ``` tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types", "@wdio/mocha-framework"] } } ``` wdio.conf.ts ``` export const config: WebdriverIO.Config = { runner: 'local', specs: ['./test/specs/**/*.ts'], maxInstances: 10, capabilities: [{ browserName: 'chrome' }, { browserName: 'firefox' }], logLevel: 'info', waitforTimeout: 10000, framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', timeout: 60000 } } ``` test/specs/login.e2e.ts ``` import { expect, browser, $ } from '@wdio/globals' describe('My Login application', () => { it('should login with valid credentials', async () => { await browser.url('https://the-internet.herokuapp.com/login') await $('#username').setValue('tomsmith') await $('#password').setValue('SuperSecretPassword!') await $('button[type="submit"]').click() await expect($('#flash')).toBeExisting() await expect($('#flash')).toHaveText( expect.stringContaining('You logged into a secure area!')) }) }) ``` ``` npx wdio run ./wdio.conf.ts ``` Each capability gets its own worker processes, so this runs the spec in both Chrome and Firefox. Other valid `browserName` values are `chromium`, `msedge` and `safari`. To run headless, add browser arguments such as `'goog:chromeOptions': { args: ['headless', 'disable-gpu'] }`. See [Run Browser Headless](/docs/capabilities.md#run-browser-headless) for Firefox and Edge; Safari has no headless mode. ## Choose your path[​](#choose-your-path "Direct link to Choose your path") End-to-end testing across browsers: * [Capabilities](/docs/capabilities.md): browser options, headless mode, browser channels (Canary, Nightly, Safari Technology Preview) and `wdio:*` driver options. * [Driver Binaries](/docs/driverbinaries.md): how automatic browser and driver setup works, and how to point at custom binaries. * [Automation Protocols](/docs/automationProtocols.md): WebDriver vs. WebDriver BiDi. * [WebDriver BiDi commands](/docs/api/webdriverBidi.md): raw BiDi protocol commands available on the `browser` object. * [Selectors](/docs/selectors.md): CSS, text, ARIA, deep (shadow DOM) and React selectors. * [Auto-waiting](/docs/autowait.md) and [Timeouts](/docs/timeouts.md): how WebdriverIO waits for elements and what to tune. * [Multi-remote](/docs/multiremote.md): control several browsers in one test, e.g. for chat or WebRTC apps. Browser capabilities that need WebDriver BiDi (Chrome, Edge and Firefox; not Safari): * [Request Mocks and Spies](/docs/mocksandspies.md): intercept, modify or stub network requests with `browser.mock()`. See also the [Mock object](/docs/api/mock.md). * [Emulation](/docs/emulation.md): emulate geolocation, media features, user agent, offline state, locale, timezone, screen and devices with `browser.emulate()`. Component and unit testing in a real browser: * [Component Testing](/docs/component-testing.md): how the Vite-based [Browser Runner](/docs/runner.md#browser-runner) works and how to set it up. * Framework guides: [React](/docs/component-testing/react.md), [Vue.js](/docs/component-testing/vue.md), [Svelte](/docs/component-testing/svelte.md), [SolidJS](/docs/component-testing/solid.md), [Preact](/docs/component-testing/preact.md), [Lit](/docs/component-testing/lit.md), [Stencil](/docs/component-testing/stencil.md). * [Mocking](/docs/component-testing/mocking.md) and [Coverage](/docs/component-testing/coverage.md) for component tests. Visual and accessibility testing: * [Visual Testing](/docs/visual-testing.md): screen, element and full-page image comparison with `@wdio/visual-service`. * [Snapshot](/docs/snapshot.md): DOM and object snapshot assertions. * [Axe Core](/docs/accessibility-testing/axe-core.md): run Deque axe accessibility scans from your tests. Scaling out: * [Selenium Grid](/docs/seleniumgrid.md), [Cloud Services](/docs/cloudservices.md) and [Docker](/docs/docker.md): run browsers remotely. * [Sharding](/docs/sharding.md): split a suite across CI machines. A component test uses the same config file with a different runner. For example, to use the React preset: wdio.conf.ts ``` export const config: WebdriverIO.Config = { runner: ['browser', { preset: 'react' }], specs: ['./src/**/*.test.tsx'], capabilities: [{ browserName: 'chrome' }], framework: 'mocha', reporters: ['spec'] } ``` The Browser Runner requires `@wdio/browser-runner`. The React preset also needs `@vitejs/plugin-react`, and the guides recommend `@testing-library/react` for rendering. Presets exist for `vue`, `svelte`, `solid`, `react`, `preact` and `stencil`. For anything else, use `viteConfig` instead. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") * Chrome fails to start in CI with "user data directory is already in use" or "DevToolsActivePort file doesn't exist": see [Headless & Display Servers](/docs/headless-and-display-servers.md#troubleshooting). * `browser.mock()` or `browser.emulate()` has no effect: the session is not using WebDriver BiDi. Check your browser (Safari has no BiDi support), your cloud vendor, and `wdio:enforceWebDriverClassic`. * Drivers or browsers can't be downloaded behind a proxy: see [Custom Driver Download Host](/docs/capabilities.md#custom-driver-download-host) and [Proxy Setup](/docs/proxy.md). * Flaky tests: see [Retry Flaky Tests](/docs/retry.md) and [Debugging](/docs/debugging.md). ## Next steps[​](#next-steps "Direct link to Next steps") * [Configuration](/docs/configuration.md) reference for every `wdio.conf.ts` option. * [TypeScript Setup](/docs/typescript.md) and [Frameworks](/docs/frameworks.md) (Mocha, Jasmine, Cucumber). * [Page Object Pattern](/docs/pageobjects.md) to structure larger suites. * [MCP](/docs/mcp.md) to let an AI agent drive a browser session through WebdriverIO. * Other platforms: [Mobile Apps](/docs/platforms/mobile.md), [Desktop Apps](/docs/platforms/desktop.md), [Extensions & Editors](/docs/platforms/apps-and-extensions.md). --- Source: https://webdriver.io/docs/driverbinaries.md # Driver Binaries To run automation based on the WebDriver protocol you need to have browser drivers set up that translate the automation commands and are able to execute them in the browser. ## Automated setup[​](#automated-setup "Direct link to Automated setup") With WebdriverIO `v8.14` and above there is no need to manually download and setup any browser drivers anymore as this is handled by WebdriverIO. All you have to do is specify the browser you want to test and WebdriverIO will do the rest. On ARM64, see [Chromedriver on ARM64](/docs/arm64-chromedriver.md) for how driver setup works on macOS, Windows and Linux, and what to do when it can't be set up automatically. ### Customizing the level of automation[​](#customizing-the-level-of-automation "Direct link to Customizing the level of automation") WebdriverIO's have three levels of automation: **1. Download and install the browser using [@puppeteer/browsers](https://www.npmjs.com/package/@puppeteer/browsers).** If you specify a `browserName`/`browserVersion` combination in the [capabilities](/docs/configuration.md#capabilities-1) configuration, WebdriverIO will download and install the requested combination, regardless of whether there's an existing installation on the machine. If you omit `browserVersion`, WebdriverIO will first try to locate and use an existing installation with [locate-app](https://www.npmjs.com/package/locate-app), otherwise it will download and install the current stable browser release. For more details on `browserVersion`, see [here](/docs/capabilities.md#automate-different-browser-channels). caution Automated browser setup does not support Microsoft Edge. Currently, only Chrome, Chromium and Firefox are supported. If you have a browser installation on a location that cannot be auto-detected by WebdriverIO, you can specify the browser binary which will disable the automated download and installation. ``` { capabilities: [ { browserName: 'chrome', // or 'firefox' or 'chromium' 'goog:chromeOptions': { // or 'moz:firefoxOptions' or 'wdio:chromedriverOptions' binary: '/path/to/chrome' }, } ] } ``` **2. Download and install the driver: Chromedriver from [Chrome for Testing](https://googlechromelabs.github.io/chrome-for-testing/), Edgedriver and Geckodriver with the [edgedriver](https://www.npmjs.com/package/edgedriver) and [geckodriver](https://www.npmjs.com/package/geckodriver) packages.** WebdriverIO will always do this, unless driver [binary](/docs/capabilities.md#binary) is specified in the configuration: ``` { capabilities: [ { browserName: 'chrome', // or 'firefox', 'msedge', 'safari', 'chromium' 'wdio:chromedriverOptions': { // or 'wdio:geckodriverOptions', 'wdio:edgedriverOptions' binary: '/path/to/chromedriver' // or 'geckodriver', 'msedgedriver' } } ] } ``` WebdriverIO downloads Chromedriver from Chrome for Testing by default, but in certain cases it will use an [Electron release](https://github.com/electron/electron/releases): * [`wdio:electronVersion`](/docs/capabilities.md#wdioelectronversion) is set, for an Electron app. It uses that release, unless `browserVersion` and `CHROMEDRIVER_CDNURL` are both set. * Chrome is older than `153.0.8001.0` on Linux ARM64, where Chrome for Testing has no Chromedriver builds (see [Chromedriver on ARM64](/docs/arm64-chromedriver.md)). It uses the last release with the same Chromium major. * The Chrome for Testing download fails, for example during an outage, and `CHROMEDRIVER_CDNURL` isn't set. It uses the last release with the same Chromium major. info WebdriverIO won't automatically download Safari driver as it is already installed on macOS. Firefox / Geckodriver Firefox uses a different versioning scheme for the browser (e.g. `stable_151.0.1`) than [Geckodriver](https://github.com/mozilla/geckodriver/releases) (e.g. `0.36.0`), so `browserVersion` is **not** used to pick the driver version. By default WebdriverIO downloads the latest Geckodriver. To pin a specific driver version, set `geckoDriverVersion` in `wdio:geckodriverOptions`: ``` { capabilities: [ { browserName: 'firefox', browserVersion: 'stable_151.0.1', 'wdio:geckodriverOptions': { geckoDriverVersion: '0.36.0' } } ] } ``` caution Avoid specifying a `binary` for the browser and omitting the corresponding driver `binary` or vice-versa. If only one of the `binary` values is specified, WebdriverIO will try to use or download a browser/driver compatible with it. However, in some scenarios it may result in an incompatible combination. Therefore, it's recommended that you always specify both to avoid any problems caused by version incompatibilities. **3. Start/stop the driver.** By default, WebdriverIO will automatically start and stop the driver using an arbitrary unused port. Specifying any of the following configuration will disable this feature which means you'll need to manually start and stop the driver: * Any value for [port](/docs/configuration.md#port). * Any value different from the default for [protocol](/docs/configuration.md#protocol), [hostname](/docs/configuration.md#hostname), [path](/docs/configuration.md#path). * Any value for both [user](/docs/configuration.md#user) and [key](/docs/configuration.md#key). ## Manual setup[​](#manual-setup "Direct link to Manual setup") The following describes how you can still set up each driver individually. You can find a list with all drivers in the [`awesome-selenium`](https://github.com/christian-bromann/awesome-selenium#driver) README. tip If you are looking to set up mobile and other UI platforms, have a look into our [Appium Setup](/docs/appium.md) guide. ### Chromedriver[​](#chromedriver "Direct link to Chromedriver") To automate Chrome you can download Chromedriver directly on the [project website](http://chromedriver.chromium.org/downloads) or through the NPM package: * npm * Yarn * pnpm * Bun ``` npm install -g chromedriver ``` ``` yarn global add chromedriver ``` ``` pnpm add -g chromedriver ``` ``` bun add --global chromedriver ``` You can then start it via: ``` chromedriver --port=4444 --verbose ``` ### Geckodriver[​](#geckodriver "Direct link to Geckodriver") To automate Firefox download the latest version of `geckodriver` for your environment and unpack it in your project directory: * NPM * Curl * Brew * Windows (64 bit / Chocolatey) * Windows (64 bit / Powershell) DevTools - npm - Yarn - pnpm - Bun ``` npm install geckodriver ``` ``` yarn add geckodriver ``` ``` pnpm add geckodriver ``` ``` bun add geckodriver ``` Linux: ``` curl -L https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz | tar xz ``` MacOS (64 bit): ``` curl -L https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-macos.tar.gz | tar xz ``` ``` brew install geckodriver ``` ``` choco install selenium-gecko-driver ``` ``` # Run as privileged session. Right-click and set 'Run as Administrator' # Use geckodriver-v0.24.0-win32.zip for 32 bit Windows $url = "https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-win64.zip" $output = "geckodriver.zip" # will drop into current directory unless defined otherwise $unzipped_file = "geckodriver" # will unzip to this folder name # By default, Powershell uses TLS 1.0 the site security requires TLS 1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Downloads Geckodriver Invoke-WebRequest -Uri $url -OutFile $output # Unzip Geckodriver Expand-Archive $output -DestinationPath $unzipped_file cd $unzipped_file # Globally Set Geckodriver to PATH [System.Environment]::SetEnvironmentVariable("PATH", "$Env:Path;$pwd\geckodriver.exe", [System.EnvironmentVariableTarget]::Machine) ``` **Note:** Other `geckodriver` releases are available [here](https://github.com/mozilla/geckodriver/releases). After download you can start the driver via: ``` /path/to/binary/geckodriver --port 4444 ``` ### Edgedriver[​](#edgedriver "Direct link to Edgedriver") You can download the driver for Microsoft Edge on the [project website](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) or as NPM package via: ``` npm install -g edgedriver edgedriver --version # prints: Microsoft Edge WebDriver 115.0.1901.203 (a5a2b1779bcfe71f081bc9104cca968d420a89ac) ``` ### Safaridriver[​](#safaridriver "Direct link to Safaridriver") Safaridriver comes pre-installed on your MacOS and can be started directly via: ``` safaridriver -p 4444 ``` --- Source: https://webdriver.io/docs/arm64-chromedriver.md # Chromedriver on ARM64 WebdriverIO sets up Chromedriver automatically on ARM64. On **macOS** (Apple silicon), Chrome for Testing publishes a native `mac-arm64` Chromedriver for every version, so there's nothing to set up. On **Windows 11 on Arm** it also works with no configuration: Chrome for Testing publishes no `win-arm64` Chromedriver, but its `win64` (x64) Chromedriver runs under Windows' transparent [x64 emulation](https://learn.microsoft.com/en-us/windows/arm/apps-on-arm-x86-emulation) and drives both an installed ARM64 Chrome and the x64 Chrome for Testing browser WebdriverIO downloads otherwise. On **Linux ARM64**, Chrome versions older than `153.0.8001.0` need a closer look, covered below. ## Linux ARM64[​](#linux-arm64 "Direct link to Linux ARM64") Chrome for Testing builds `linux-arm64` Chromedriver from Chrome **`153.0.8001.0`** onward, and WebdriverIO uses it directly. For an older Chrome or Chromium, such as one set as `goog:chromeOptions.binary`, it downloads the Chromedriver bundled in an [Electron release](https://github.com/electron/electron/releases) which matches the required Chromium major version. This download comes from GitHub even when `CHROMEDRIVER_CDNURL` is set, because Chrome for Testing has no `linux-arm64` Chromedriver below `153.0.8001.0` for a mirror to serve; offline, use your distribution's Chromium and driver as shown [below](#no-electron-release-ships-a-matching-chromedriver). Chrome for Testing has no `linux-arm64` browser builds before `153.0.8001.0` either, so pin `browserVersion` below that only together with `goog:chromeOptions.binary` pointing at an ARM64 browser. ## Electron apps[​](#electron-apps "Direct link to Electron apps") `wdio:electronVersion` downloads the Chromedriver bundled with a given Electron release, on every ARM64 platform. For an Electron app, the Electron service sets it from the app's Electron version. See [Capabilities](/docs/capabilities.md#wdioelectronversion) for details. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### No Electron release ships a matching Chromedriver[​](#no-electron-release-ships-a-matching-chromedriver "Direct link to No Electron release ships a matching Chromedriver") A few Chromium majors, such as 145, never shipped in an Electron release. WebdriverIO then fails rather than installing a mismatched driver: ``` Chrome for Testing has no linux-arm64 Chromedriver before v153.0.8001.0, and no Electron release ships one for Chrome v145.0.7632.117. See https://webdriver.io/docs/arm64-chromedriver ``` To resolve it: * **Use Chrome/Chromium `153.0.8001.0` or later** so Chrome for Testing serves the driver directly. * **On Debian, use its Chromium and driver**, a matched arm64 pair: ``` sudo apt-get install -y chromium chromium-driver ``` wdio.conf.ts ``` export const config: WebdriverIO.Config = { // ... capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { binary: '/usr/bin/chromium' }, 'wdio:chromedriverOptions': { binary: '/usr/bin/chromedriver' } }] } ``` * **Bring your own Chromedriver** with `wdio:chromedriverOptions.binary`, which disables the download entirely. ## Related[​](#related "Direct link to Related") * [Driver Binaries](/docs/driverbinaries.md): how WebdriverIO downloads and caches browser drivers, including the fallback when Chrome for Testing fails. * [Capabilities](/docs/capabilities.md#wdioelectronversion): the `wdio:electronVersion` option. --- Source: https://webdriver.io/docs/extension-testing/web-extensions.md # Web Extension Testing WebdriverIO is the ideal tool to automate a browser. Web Extensions are a part of the browser and can be automated in the same way. Whenever your web extension uses content scripts to run JavaScript on websites or offer a popup modal, you can run an e2e test for that using WebdriverIO. Load the extension before the first navigation with the capability setup below. To install and remove one in the middle of a [WebDriver BiDi](https://w3c.github.io/webdriver-bidi/#module-webExtension) session, use [`installExtension`](/docs/api/browser/installExtension.md) and [`uninstallExtension`](/docs/api/browser/uninstallExtension.md). ## Loading a Web Extension into the Browser[​](#loading-a-web-extension-into-the-browser "Direct link to Loading a Web Extension into the Browser") As a first step we have to load the extension under test into the browser as part of our session. This works differently for Chrome and Firefox. info These docs leave out Safari web extensions as their support for it is way behind and user demand not high. Safari also has no WebDriver BiDi session, so [`installExtension`](/docs/api/browser/installExtension.md) does not cover Safari. If you are building a web extension for Safari, please [raise an issue](https://github.com/webdriverio/webdriverio/issues/new?assignees=\&labels=Docs+%F0%9F%93%96%2CNeeds+Triaging+%E2%8F%B3\&template=documentation.yml\&title=%5B%F0%9F%93%96+Docs%5D%3A+%3Ctitle%3E) and collaborate on including it here as well. ### Chrome[​](#chrome "Direct link to Chrome") Loading a web extension in Chrome can be done through providing a `base64` encoded string of the `crx` file or by providing a path to the web extension folder. The easiest is just to do the latter by defining your Chrome capabilities as following: ``` import path from 'node:path' import url from 'node:url' const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) export const config = { // ... capabilities: [{ browserName, 'goog:chromeOptions': { // given your wdio.conf.js is in the root directory and your compiled // web extension files are located in the `./dist` folder args: [`--load-extension=${path.join(__dirname, '..', '..', 'dist')}`] } }] } ``` info If you automate a different browser than Chrome, e.g. Brave, Edge or Opera, chances are that the browser option match with the example above, just using a different capability name, e.g. `ms:edgeOptions`. If you compile your extension as `.crx` file using e.g. the [crx](https://www.npmjs.com/package/crx) NPM package, you can also inject the bundled extension via: ``` import path from 'node:path' import url from 'node:url' const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) const extPath = path.join(__dirname, `web-extension-chrome.crx`) const chromeExtension = (await fs.readFile(extPath)).toString('base64') export const config = { // ... capabilities: [{ browserName, 'goog:chromeOptions': { extensions: [chromeExtension] } }] } ``` ### Firefox[​](#firefox "Direct link to Firefox") To create a Firefox profile that includes extensions you can use the [Firefox Profile Service](/docs/firefox-profile-service.md) to set up your session accordingly. However you might run into issues where your local developed extension can't be loaded due to signing issues. In this case you can also load an extension in the `before` hook via the [`installAddOn`](/docs/api/gecko.md#installaddon) command, e.g.: ``` import path from 'node:path' import url from 'node:url' const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) const extensionPath = path.resolve(__dirname, `web-extension.xpi`) export const config = { // ... before: async (capabilities) => { const browserName = (capabilities as WebdriverIO.Capabilities).browserName if (browserName === 'firefox') { const extension = await fs.readFile(extensionPath) await browser.installAddOn(extension.toString('base64'), true) } } } ``` In order to generate an `.xpi` file, it is recommended to use the [`web-ext`](https://www.npmjs.com/package/web-ext) NPM package. You can bundle your extension using the following example command: ``` npx web-ext build -s dist/ -a . -n web-extension-firefox.xpi ``` ## Install an extension during the session[​](#install-an-extension-during-the-session "Direct link to Install an extension during the session") Since v10, [`browser.installExtension`](/docs/api/browser/installExtension.md) and [`browser.uninstallExtension`](/docs/api/browser/uninstallExtension.md) install a web extension in the middle of a WebDriver BiDi session and return its id. Use them when the extension must not be present at launch, or when the same test installs it, exercises it, and removes it. The capability setup and `installAddOn` above stay the way to load an extension before the first navigation. `installExtension` does not replace them. `browser.webExtensionInstall` and `browser.webExtensionUninstall` stay available when you want the [spec payload](https://w3c.github.io/webdriver-bidi/#command-webExtension-install) yourself. test/specs/extension.e2e.ts ``` import path from 'node:path' import url from 'node:url' import { browser, expect } from '@wdio/globals' const extensionPath = path.resolve( path.dirname(url.fileURLToPath(import.meta.url)), '../../dist' ) describe('web extension', () => { it('installs and removes the extension', async () => { const extensionId = await browser.installExtension(extensionPath) expect(extensionId).not.toEqual('') await browser.url('https://webdriver.io') await browser.uninstallExtension(extensionId) }) }) ``` `installExtension` accepts three inputs: | Input | Payload sent to the browser | | -------------------------------- | ------------------------------------------------------------------------------------------------- | | A directory path | `{ type: 'path', path }` after `path.resolve`. The browser has to be able to read that directory. | | A `.zip`, `.xpi`, or `.crx` path | `{ type: 'archivePath', path }` after `path.resolve`. | | `{ base64: string }` | `{ type: 'base64', value }`. Archive bytes. Any other object is rejected. | A string path is always resolved on the test runner. On a remote session — a hostname other than `localhost`, `127.0.0.1`, or `::1`, or a cloud `user` and `key` — that path is not a path on the browser machine. The command reads an archive, or zips a directory in memory, and sends `base64`. You do not branch on local versus remote yourself. Local sessions send `path` or `archivePath` and do not read the bytes. Point a directory at the extension root, the folder that contains `manifest.json`. The session has to speak WebDriver BiDi. A classic session throws `installExtension requires a WebDriver BiDi session (webExtension.install)`. A browser that implements BiDi but not this module fails the command with `unsupported operation` (or `unknown command` when the module is absent). A bad archive fails with `invalid web extension`. Uninstalling an id the browser does not know fails with `no such web extension`. `uninstallExtension` takes the id string `installExtension` returned. ### Chromium[​](#chromium "Direct link to Chromium") Chrome and Edge implement `webExtension.install` and leave it switched off until you start the browser with `--enable-unsafe-extension-debugging` and `--remote-debugging-pipe`. Chrome 136 and newer also require `--user-data-dir` whenever `--remote-debugging-pipe` is set. Without those arguments the command fails with `unknown error - Method not available`. `--remote-debugging-pipe` is the pipe between the driver and the browser. The BiDi session still uses `webSocketUrl`. wdio.conf.ts ``` import fs from 'node:fs' import os from 'node:os' import path from 'node:path' const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wdio-chrome-')) export const config: WebdriverIO.Config = { // ... capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { args: [ '--enable-unsafe-extension-debugging', '--remote-debugging-pipe', `--user-data-dir=${userDataDir}` ] } }] } ``` Use `ms:edgeOptions` for Edge. Firefox loads the extension in a normal BiDi session and does not need these arguments. ## Tips & Tricks[​](#tips--tricks "Direct link to Tips & Tricks") The following section contains a set useful tips and tricks that can be helpful when testing a web extension. ### Test Popup Modal in Chrome[​](#test-popup-modal-in-chrome "Direct link to Test Popup Modal in Chrome") If you define a `default_popup` browser action entry in your [extension manifest](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action) you can test that HTML page directly, since clicking on the extension icon in the browser top bar won't work. Instead, you have to open the popup html file directly. In Chrome this works by retrieving the extension ID and opening the popup page through `browser.url('...')`. The behavior on that page will be the same as within the popup. To do so we recommend to write the following custom command: ``` export async function openExtensionPopup (this: WebdriverIO.Browser, extensionName: string, popupUrl = 'index.html') { if ((this.capabilities as WebdriverIO.Capabilities).browserName !== 'chrome') { throw new Error('This command only works with Chrome') } await this.url('chrome://extensions/') const extensions = await this.$$('extensions-item') const extension = await extensions.find(async (ext) => ( await ext.$('#name').getText()) === extensionName ) if (!extension) { const installedExtensions = await extensions.map((ext) => ext.$('#name').getText()) throw new Error(`Couldn't find extension "${extensionName}", available installed extensions are "${installedExtensions.join('", "')}"`) } const extId = await extension.getAttribute('id') await this.url(`chrome-extension://${extId}/popup/${popupUrl}`) } declare global { namespace WebdriverIO { interface Browser { openExtensionPopup: typeof openExtensionPopup } } } ``` In your `wdio.conf.js` you can import this file and register the custom command in your `before` hook, e.g.: ``` import { browser } from '@wdio/globals' import { openExtensionPopup } from './support/customCommands' export const config: WebdriverIO.Config = { // ... before: () => { browser.addCommand('openExtensionPopup', openExtensionPopup) } } ``` Now, in your test, you can access the popup page via: ``` await browser.openExtensionPopup('My Web Extension') ``` --- Source: https://webdriver.io/docs/component-testing.md # Component Testing With WebdriverIOs [Browser Runner](/docs/runner.md#browser-runner) you can run tests within an actual desktop or mobile browser while using WebdriverIO and the WebDriver protocol to automate and interact what gets rendered on the page. This approach has [many advantages](/docs/runner.md#browser-runner) compared to other test frameworks that only allow testing against [JSDOM](https://www.npmjs.com/package/jsdom). ## Browser support[​](#browser-support "Direct link to Browser support") The browser runner executes the test bundle in the browser. That bundle runs in Chrome 90, Edge 90, Firefox 90 and Safari 14.1, and in later versions of those browsers. End-to-end tests run in Node.js. Code passed to [`browser.execute`](/docs/api/browser/execute.md) runs in the automated browser instead, which can be older than the versions above. Keep that code at ES2021. ## How does it Work?[​](#how-does-it-work "Direct link to How does it Work?") The Browser Runner uses [Vite](https://vitejs.dev/) to render a test page and initialize a test framework to run your tests in the browser. Currently it only supports Mocha but Jasmine and Cucumber are [on the roadmap](https://github.com/orgs/webdriverio/projects/1). This allows to test any kind of components even for projects that don't use Vite. The Vite server is started by the WebdriverIO testrunner and configured so that you can use all reporter and services as you used to for normal e2e tests. Furthermore it initializes a [`browser`](/docs/api/browser.md) instance that allows you to access a subset of the [WebdriverIO API](/docs/api.md) to interact with the any elements on the page. Similar as e2e tests you can access that instance through the `browser` variable attached to the global scope or by importing it from `@wdio/globals` depending on how [`injectGlobals`](/docs/api/globals.md) is set. WebdriverIO has built-in support for the following frameworks: * [**Nuxt**](https://nuxt.com/): WebdriverIO's testrunner detects a Nuxt application and automatically sets up your project composables and helps mock out the Nuxt backend, read more in the [Nuxt docs](/docs/component-testing/vue.md#testing-vue-components-in-nuxt) * [**TailwindCSS**](https://tailwindcss.com/): WebdriverIO's testrunner detects if you are using TailwindCSS and loads the environment properly into the test page ## Setup[​](#setup "Direct link to Setup") To set-up WebdriverIO for unit or component testing in the browser, initiate a new WebdriverIO project via: ``` npm init wdio@latest ./ # or yarn create wdio ./ ``` Once the configuration wizard starts, pick `browser` for running unit and component testing and choose one of the presets if desired otherwise go with *"Other"* if you only want to run basic unit tests. You can also configure a custom Vite configuration if you use Vite already in your project. For more information check out all [runner options](/docs/runner.md#runner-options). info **Note:** WebdriverIO by default will run browser tests in CI headlessly, e.g. a `CI` environment variable is set to `'1'` or `'true'`. You can manually configure this behavior using the [`headless`](/docs/runner.md#headless) option for the runner. At the end of this process you should find a `wdio.conf.js` that contains various WebdriverIO configurations, including a `runner` property, e.g.: wdio.comp.conf.js ``` loading... ``` [View on GitHub]() By defining different [capabilities](/docs/configuration.md#capabilities) you can run your tests in different browser, in parallel if desired. If you are still unsure how everything works, watch the following tutorial on how to get started with Component Testing in WebdriverIO: ## Test Harness[​](#test-harness "Direct link to Test Harness") It is totally up to you what you want to run in your tests and how you like to render the components. However we recommend to use the [Testing Library](https://testing-library.com/) as utility framework as it provides plugins for various component frameworks, such as React, Preact, Svelte and Vue. It is very useful for rendering components into the test page and it automatically cleans up these components after every test. You can mix Testing Library primitives with WebdriverIO commands as you wish, e.g.: component-testing/svelte-example.js ``` loading... ``` [View on GitHub]() **Note:** using render methods from Testing Library helps remove created components between the tests. If you don't use Testing Library ensure to attach your test components to a container that gets cleaned up between tests. ## Setup Scripts[​](#setup-scripts "Direct link to Setup Scripts") You can set up your tests by running arbitrary scripts in Node.js or in the browser, e.g. injecting styles, mocking browser APIs or connecting to a 3rd party service. The WebdriverIO [hooks](/docs/configuration.md#hooks) can be used to run code in Node.js while the [`mochaOpts.require`](/docs/frameworks.md#require) allows you to import scripts into the browser before tests are loaded, e.g.: ``` export const config = { // ... mochaOpts: { ui: 'tdd', // provide a setup script to run in the browser require: './__fixtures__/setup.js' }, before: () => { // set up test environment in Node.js } // ... } ``` For example, if you like to mock all [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) calls in your test with the following set-up script: ``` import { fn } from '@wdio/browser-runner' // run code before all tests are loaded window.fetch = fn() export const mochaGlobalSetup = () => { // run code after test file is loaded } export const mochaGlobalTeardown = () => { // run code after spec file was executed } ``` Now in your tests you can provide custom response values for all browser requests. Read more on global fixtures in the [Mocha docs](https://mochajs.org/#global-fixtures). ## Watch Test and Application Files[​](#watch-test-and-application-files "Direct link to Watch Test and Application Files") There are multiple ways how you can debug your browser tests. The easiest is to start the WebdriverIO testrunner with the `--watch` flag, e.g.: ``` $ npx wdio run ./wdio.conf.js --watch ``` This will run through all tests initially and halt once all are run. You can then make changes to individual files which then will be rerun individually. If you set a [`filesToWatch`](/docs/configuration.md#filestowatch) pointing to your application files, it will re-run all tests when changes to your app are being made. ## Debugging[​](#debugging "Direct link to Debugging") While it is not (yet) possible to set breakpoints in your IDE and have them being recognized by the remote browser, you can use the [`debug`](/docs/api/browser/debug.md) command to stop the test at any point. This allows you to open DevTools to then debug the test by setting breakpoints in the [sources tab](https://buddy.works/tutorials/debugging-javascript-efficiently-with-chrome-devtools). When the `debug` command is called, you will also get a Node.js repl interface in your terminal, saying: ``` The execution has stopped! You can now go into the browser or use the command line as REPL (To exit, press ^C again or type .exit) ``` Press `Ctrl` or `Command` + `c` or enter `.exit` to continue with the test. ## Run using a Selenium Grid[​](#run-using-a-selenium-grid "Direct link to Run using a Selenium Grid") If you have a [Selenium Grid](https://www.selenium.dev/documentation/grid/) set up and run your browser through that grid, you have to set the `host` browser runner option to allow the browser, to access the right host where the test files are being served, e.g.: ``` export const config: WebdriverIO.Config = { runner: ['browser', { // network IP of the machine that runs the WebdriverIO process host: 'http://172.168.0.2' }] } ``` This will ensure the browser correctly opens the right server instance hosted on the instance that runs the WebdriverIO tests. ## Examples[​](#examples "Direct link to Examples") You can find various examples for testing components using popular component frameworks in our [example repository](https://github.com/webdriverio/component-testing-examples). --- Source: https://webdriver.io/docs/component-testing/coverage.md # Coverage WebdriverIO's browser runner supports code coverage reporting using [`istanbul`](https://istanbul.js.org/). The testrunner will automatically instrument your code using Vite and capture code coverage for you. ## How it Works[​](#how-it-works "Direct link to How it Works") The `@wdio/browser-runner` uses Vite to serve your application. When you enable coverage, it adds a plugin to the Vite server that attempts to instrument your source code on the fly as it is requested by the browser. Important **Do not navigate away from the test runner!** Code coverage relies on the files being served and instrumented by the local Vite server started by WebdriverIO. If you use `browser.url('http://...')` or `browser.url('file://...')` to navigate to a different page, you are leaving the instrumented environment. Your code will run, but **no coverage will be collected**. **Correct Approach (Component Testing):** Render your component or import your module directly in the test file. ``` import { myFunction } from '../src/utils.js' it('should cover my function', () => { myFunction() // This is covered }) ``` **Incorrect Approach (E2E Style):** ``` it('will not have coverage', async () => { // ❌ navigating away breaks instrumentation await browser.url('http://localhost:3000') }) ``` ## Setup[​](#setup "Direct link to Setup") In order to enable code coverage reporting, enable it through the WebdriverIO browser runner configuration, e.g.: ``` export const config = { // ... runner: ['browser', { preset: process.env.WDIO_PRESET, coverage: { enabled: true } }], // ... } ``` Checkout all [coverage options](/docs/runner.md#coverage-options), to learn how to properly configure it. Configuration Tips If you are testing non-standard files (like inline scripts in `.html`) or if your files are not being picked up, you may need to explicitly verify your `include` and `extension` options: ``` coverage: { enabled: true, // Explicitly target your source files if default resolution fails include: ['src/**/*.js', 'src/**/*.vue'], // Add .html if you have inline scripts extension: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.html'] } ``` ## Ignoring Code[​](#ignoring-code "Direct link to Ignoring Code") There may be some sections of your codebase that you wish to purposefully exclude from coverage tracking, to do so you can use the following parsing hints: * `/* istanbul ignore if */`: ignore the next if statement. * `/* istanbul ignore else */`: ignore the else portion of an if statement. * `/* istanbul ignore next */`: ignore the next thing in the source-code ( functions, if statements, classes, you name it). * `/* istanbul ignore file */`: ignore an entire source-file (this should be placed at the top of the file). info It is recommended to exclude your test files from the coverage reporting as it could cause errors, e.g. when calling the `execute` command. If you like to keep them in your report, ensure your exclude instrumenting them via: ``` await browser.execute(/* istanbul ignore next */() => { // ... }) ``` --- Source: https://webdriver.io/docs/component-testing/mocking.md # Mocking When writing tests it's only a matter of time before you need to create a "fake" version of an internal — or external — service. This is commonly referred to as mocking. WebdriverIO provides utility functions to help you out. You can `import { fn, spyOn, mock, unmock } from '@wdio/browser-runner'` to access it. See more information about the available mocking utilities in the [API docs](/docs/api/modules.md#wdiobrowser-runner). ## Functions[​](#functions "Direct link to Functions") In order to validate whether certain function handler are called as part of your component tests, the `@wdio/browser-runner` module exports mocking primitives you can use to test, if these functions have been called. You can import these methods via: ``` import { fn, spyOn } from '@wdio/browser-runner' ``` By importing `fn` you can create a spy function (mock) to track its execution and with `spyOn` track a method on an already created object. * Mocks * Spies The full example can be found in the [Component Testing Example](https://github.com/webdriverio/component-testing-examples/blob/main/react-typescript-vite/src/tests/LoginForm.test.tsx) repository. ``` import React from 'react' import { $, expect } from '@wdio/globals' import { fn } from '@wdio/browser-runner' import { Key } from 'webdriverio' import { render } from '@testing-library/react' import LoginForm from '../components/LoginForm' describe('LoginForm', () => { it('should call onLogin handler if username and password was provided', async () => { const onLogin = fn() render() await $('input[name="username"]').setValue('testuser123') await $('input[name="password"]').setValue('s3cret') await browser.keys(Key.Enter) /** * verify the handler was called */ expect(onLogin).toBeCalledTimes(1) expect(onLogin).toBeCalledWith(expect.equal({ username: 'testuser123', password: 's3cret' })) }) }) ``` The full example can be found in the [examples](https://github.com/webdriverio/webdriverio/blob/main/examples/wdio/browser-runner/lit.test.js) directory. ``` import { expect, $ } from '@wdio/globals' import { spyOn } from '@wdio/browser-runner' import { html, render } from 'lit' import { SimpleGreeting } from './components/LitComponent.ts' const getQuestionFn = spyOn(SimpleGreeting.prototype, 'getQuestion') describe('Lit Component testing', () => { it('should render component', async () => { render( html``, document.body ) const innerElem = await $('simple-greeting').$('p') expect(await innerElem.getText()).toBe('Hello, WebdriverIO! How are you today?') }) it('should render with mocked component function', async () => { getQuestionFn.mockReturnValue('Does this work?') render( html``, document.body ) const innerElem = await $('simple-greeting').$('p') expect(await innerElem.getText()).toBe('Hello, WebdriverIO! Does this work?') }) }) ``` WebdriverIO just re-exports [`@vitest/spy`](https://www.npmjs.com/package/@vitest/spy) here which is a lightweight Jest compatible spy implementation that can be used with WebdriverIOs [`expect`](/docs/api/expect-webdriverio.md) matchers. You can find more documentation on these mock functions on the [Vitest project page](https://vitest.dev/api/mock.html). Of course, you can also install and import any other spy framework, e.g. [SinonJS](https://sinonjs.org/), as long as it supports the browser environment. ## Modules[​](#modules "Direct link to Modules") Mock local modules or observe third-party-libraries, that are invoked in some other code, allowing you to test arguments, output or even redeclare its implementation. There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency. ### Mocking File Imports[​](#mocking-file-imports "Direct link to Mocking File Imports") Let's imagine our component is importing a utility method from a file to handle a click. ``` export function handleClick () { // handler implementation } ``` In our component the click handler is used as following: ``` import { handleClick } from './utils.js' @customElement('simple-button') export class SimpleButton extends LitElement { render() { return html`` } } ``` To mock the `handleClick` from `utils.js` we can use the `mock` method in our test as following: ``` import { expect, $ } from '@wdio/globals' import { mock, fn } from '@wdio/browser-runner' import { html, render } from 'lit' import { SimpleButton } from './LitComponent.ts' import { handleClick } from './utils.js' /** * mock named export "handleClick" of `utils.ts` file */ mock('./utils.ts', () => ({ handleClick: fn() })) describe('Simple Button Component Test', () => { it('call click handler', async () => { render(html``, document.body) await $('simple-button').$('button').click() expect(handleClick).toHaveBeenCalledTimes(1) }) }) ``` ### Mocking Dependencies[​](#mocking-dependencies "Direct link to Mocking Dependencies") Suppose we have a class that fetches users from our API. The class uses [`axios`](https://github.com/axios/axios) to call the API then returns the data attribute which contains all the users: ``` import axios from 'axios'; class Users { static all() { return axios.get('/users.json').then(resp => resp.data) } } export default Users ``` Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the `mock(...)` function to automatically mock the axios module. Once we mock the module we can provide a [`mockResolvedValue`](https://vitest.dev/api/mock.html#mockresolvedvalue) for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. ``` import axios from 'axios'; // imports defined mock import { mock, fn } from '@wdio/browser-runner' import Users from './users.js' /** * mock default export of `axios` dependency */ mock('axios', () => ({ default: { get: fn() } })) describe('User API', () => { it('should fetch users', async () => { const users = [{name: 'Bob'}] const resp = {data: users} axios.get.mockResolvedValue(resp) // or you could use the following depending on your use case: // axios.get.mockImplementation(() => Promise.resolve(resp)) const data = await Users.all() expect(data).toEqual(users) }) }) ``` ## Partials[​](#partials "Direct link to Partials") Subsets of a module can be mocked and the rest of the module can keep their actual implementation: ``` export const foo = 'foo'; export const bar = () => 'bar'; export default () => 'baz'; ``` The original module will be passed into the mock factory which you can use to e.g. partially mock a dependency: ``` import { mock, fn } from '@wdio/browser-runner' import defaultExport, { bar, foo } from './foo-bar-baz.js'; mock('./foo-bar-baz.js', async (originalModule) => { // Mock the default export and named export 'foo' // and propagate named export from the original module return { __esModule: true, ...originalModule, default: fn(() => 'mocked baz'), foo: 'mocked foo', } }) describe('partial mock', () => { it('should do a partial mock', () => { const defaultExportResult = defaultExport(); expect(defaultExportResult).toBe('mocked baz'); expect(defaultExport).toHaveBeenCalled(); expect(foo).toBe('mocked foo'); expect(bar()).toBe('bar'); }) }) ``` ## Manual Mocks[​](#manual-mocks "Direct link to Manual Mocks") Manual mocks are defined by writing a module in a `__mocks__/` (see also `automockDir` option) subdirectory. If the module you are mocking is a Node module (e.g.: `lodash`), the mock should be placed in the `__mocks__` directory and will be automatically mocked. There's no need to explicitly call `mock('module_name')`. Scoped modules (also known as scoped packages) can be mocked by creating a file in a directory structure that matches the name of the scoped module. For example, to mock a scoped module called `@scope/project-name`, create a file at `__mocks__/@scope/project-name.js`, creating the `@scope/` directory accordingly. ``` . ├── config ├── __mocks__ │ ├── axios.js │ ├── lodash.js │ └── @scope │ └── project-name.js ├── node_modules └── views ``` When a manual mock exists for a given module, WebdriverIO will use that module when explicitly calling `mock('moduleName')`. However, when automock is set to true, the manual mock implementation will be used instead of the automatically created mock, even if `mock('moduleName')` is not called. To opt out of this behavior you will need to explicitly call `unmock('moduleName')` in tests that should use the actual module implementation, e.g.: ``` import { unmock } from '@wdio/browser-runner' unmock('lodash') ``` ## Hoisting[​](#hoisting "Direct link to Hoisting") In order to get mocking to work in the browser, WebdriverIO rewrites the test files and hoists the mock calls above everything else (see also [this blog post](https://www.coolcomputerclub.com/posts/jest-hoist-await/) on the hoisting problem in Jest). This limits the way you can pass in variables into the mock resolver, e.g.: ``` import dep from 'dependency' const variable = 'foobar' /** * ❌ this fails as `dep` and `variable` are not defined inside the mock resolver */ mock('./some/module.ts', () => ({ exportA: dep, exportB: variable })) ``` To fix this you have to define all used variables inside the resolver, e.g.: ``` /** * ✔️ this works as all variables are defined within the resolver */ mock('./some/module.ts', async () => { const dep = await import('dependency') const variable = 'foobar' return { exportA: dep, exportB: variable } }) ``` ## Requests[​](#requests "Direct link to Requests") If you are looking for mocking browser requests, e.g. API calls, head over to the [Request Mock and Spies](/docs/mocksandspies.md) section. In component tests, use an absolute URL pattern with a fixed protocol and hostname for `browser.mock()`, such as `https://api.webdriver.io/api/*`. A host-less pattern such as `*/api/*` intercepts every request of the page, including the browser runner's own Vite and driver traffic. A single `*` also matches slashes. In a string pattern, `**` is the same as `*`; in a `URLPattern` object, use a single `*`. See [creating a mock](/docs/mocksandspies.md#creating-a-mock). --- Source: https://webdriver.io/docs/component-testing/lit.md # Lit Lit is a simple library for building fast, lightweight web components. Testing Lit web components with WebdriverIO is very easy thanks to WebdriverIOs [shadow DOM selectors](/docs/selectors.md#deep-selectors) you can query in shadow roots nested elements with just one single command. ## Setup[​](#setup "Direct link to Setup") To setup WebdriverIO within your Lit project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. For Lit you don't need a preset as Lit web components don't need to run through a compiler, they are pure web component enhancements. Once set-up, you can start the tests by running: ``` npx wdio run ./wdio.conf.js ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following Lit component: ./components/Component.ts ``` import { LitElement, css, html } from 'lit' import { customElement, property } from 'lit/decorators.js' @customElement('simple-greeting') export class SimpleGreeting extends LitElement { @property() name?: string = 'World' // Render the UI as a function of component state render() { return html`

Hello, ${this.name}!

` } } ``` In order test the component you have to render it into the test page before the test starts and ensure it gets cleaned up afterwards: lit.test.js ``` import expect from 'expect' import { waitFor } from '@testing-library/dom' // import Lit component import './components/Component.ts' describe('Lit Component testing', () => { let elem: HTMLElement beforeEach(() => { elem = document.createElement('simple-greeting') }) it('should render component', async () => { elem.setAttribute('name', 'WebdriverIO') document.body.appendChild(elem) await waitFor(() => { expect(elem.shadowRoot.textContent).toBe('Hello, WebdriverIO!') }) }) afterEach(() => { elem.remove() }) }) ``` You can find a full example of a WebdriverIO component test suite for Lit in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/lit-typescript-vite). --- Source: https://webdriver.io/docs/component-testing/vue.md # Vue.js [Vue.js](https://vuejs.org/) is an approachable, performant and versatile framework for building web user interfaces. You can test Vue.js components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner.md#browser-runner). ## Setup[​](#setup "Direct link to Setup") To setup WebdriverIO within your Vue.js project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. Make sure to select `vue` as preset within your runner options, e.g.: ``` // wdio.conf.js export const config = { // ... runner: ['browser', { preset: 'vue' }], // ... } ``` info If you are already using [Vite](https://vitejs.dev/) as development server you can also just re-use your configuration in `vite.config.ts` within your WebdriverIO config. For more information, see `viteConfig` in [runner options](/docs/runner.md#runner-options). The Vue preset requires `@vitejs/plugin-vue` to be installed. Also we recommend using [Testing Library](https://testing-library.com/) for rendering the component into the test page. Therefor you'll need to install the following additional dependencies: * npm * Yarn * pnpm * Bun ``` npm install --save-dev @testing-library/vue @vitejs/plugin-vue ``` ``` yarn add --dev @testing-library/vue @vitejs/plugin-vue ``` ``` pnpm add --save-dev @testing-library/vue @vitejs/plugin-vue ``` ``` bun add --dev @testing-library/vue @vitejs/plugin-vue ``` You can then start the tests by running: ``` npx wdio run ./wdio.conf.js ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following Vue.js component: ./components/Component.vue ``` ``` In your test render the component into the DOM and run assertions on it. We recommend to either use [`@vue/test-utils`](https://test-utils.vuejs.org/) or [`@testing-library/vue`](https://testing-library.com/docs/vue-testing-library/intro/) to attach the component to the test page. To interact with the component use WebdriverIO commands as they behave more close to actual user interactions, e.g.: * @vue/test-utils * @testing-library/vue vue.test.js ``` import { $, expect } from '@wdio/globals' import { mount } from '@vue/test-utils' import Component from './components/Component.vue' describe('Vue Component Testing', () => { it('increments value on click', async () => { // The render method returns a collection of utilities to query your component. const wrapper = mount(Component, { attachTo: document.body }) expect(wrapper.text()).toContain('Times clicked: 0') const button = await $('aria/increment') // Dispatch a native click event to our button element. await button.click() await button.click() expect(wrapper.text()).toContain('Times clicked: 2') await expect($('p=Times clicked: 2')).toExist() // same assertion with WebdriverIO }) }) ``` vue.test.js ``` import { $, expect } from '@wdio/globals' import { render } from '@testing-library/vue' import Component from './components/Component.vue' describe('Vue Component Testing', () => { it('increments value on click', async () => { // The render method returns a collection of utilities to query your component. const { getByText } = render(Component) // getByText returns the first matching node for the provided text, and // throws an error if no elements match or if more than one match is found. getByText('Times clicked: 0') const button = await $(getByText('increment')) // Dispatch a native click event to our button element. await button.click() await button.click() getByText('Times clicked: 2') // assert with Testing Library await expect($('p=Times clicked: 2')).toExist() // assert with WebdriverIO }) }) ``` You can find a full example of a WebdriverIO component test suite for Vue.js in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/vue-typescript-vite). ## Testing Async Components in Vue3[​](#testing-async-components-in-vue3 "Direct link to Testing Async Components in Vue3") If you are using Vue v3 and are testing [async components](https://vuejs.org/guide/built-ins/suspense.html#async-setup) like the following: ``` ``` We recommend to use [`@vue/test-utils`](https://www.npmjs.com/package/@vue/test-utils) and a little suspense wrapper to get the component rendered. Unfortunately [`@testing-library/vue`](https://github.com/testing-library/vue-testing-library/issues/230) has no support for this yet. Create a `helper.ts` file with the following content: ``` import { mount, type VueWrapper as VueWrapperImport } from '@vue/test-utils' import { Suspense } from 'vue' export type VueWrapper = VueWrapperImport const scheduler = typeof setImmediate === 'function' ? setImmediate : setTimeout export function flushPromises(): Promise { return new Promise((resolve) => { scheduler(resolve, 0) }) } export function wrapInSuspense( component: ReturnType, { props }: { props: object }, ): ReturnType { return defineComponent({ render() { return h( 'div', { id: 'root' }, h(Suspense, null, { default() { return h(component, props) }, fallback: h('div', 'fallback'), }), ) }, }) } export function renderAsyncComponent(vueComponent: ReturnType, props: object): VueWrapper{ const component = wrapInSuspense(vueComponent, { props }) return mount(component, { attachTo: document.body }) } ``` Then import and test the component as following: ``` import { $, expect } from '@wdio/globals' import { renderAsyncComponent, flushPromises, type VueWrapper } from './helpers.js' import AsyncComponent from '/components/SomeAsyncComponent.vue' describe('Testing Async Components', () => { let wrapper: VueWrapper it('should display component correctly', async () => { const props = {} wrapper = renderAsyncComponent(AsyncComponent, { props }) await flushPromises() await expect($('...')).toBePresent() }) afterEach(() => { wrapper.unmount() }) }) ``` ## Testing Vue Components in Nuxt[​](#testing-vue-components-in-nuxt "Direct link to Testing Vue Components in Nuxt") If you are using the web framework [Nuxt](https://nuxt.com/), WebdriverIO will automatically enable the [auto-import](https://nuxt.com/docs/guide/concepts/auto-imports) feature and makes testing your Vue components and Nuxt pages easy. However any [Nuxt modules](https://nuxt.com/modules) that you might define in your config and requires context to the Nuxt application can not be supported. **Reasons for that are:** * WebdriverIO can't initiate a Nuxt application soley in a browser environment * Having component tests depend too much on the Nuxt environment creates complexity and we recommend to run these tests as e2e tests info WebdriverIO also provides a service for running e2e tests on Nuxt applications, see [`webdriverio-community/wdio-nuxt-service`](https://github.com/webdriverio-community/wdio-nuxt-service) for information. ### Mocking built-in composables[​](#mocking-built-in-composables "Direct link to Mocking built-in composables") In case your component uses a native Nuxt composable, e.g. [`useNuxtData`](https://nuxt.com/docs/api/composables/use-nuxt-data), WebdriverIO will automatically mock these functions and allows you to modify their behavior or assert against them, e.g.: ``` import { mocked } from '@wdio/browser-runner' // e.g. your component uses calls `useNuxtData` the following way // `const { data: posts } = useNuxtData('posts')` // in your test you can assert against it expect(useNuxtData).toBeCalledWith('posts') // and change their behavior mocked(useNuxtData).mockReturnValue({ data: [...] }) ``` ### Handling 3rd party composables[​](#handling-3rd-party-composables "Direct link to Handling 3rd party composables") All [3rd party modules](https://nuxt.com/modules) that can supercharge your Nuxt project can't automatically get mocked. In those cases you need to manually mock them, e.g. given your application uses the [Supabase](https://nuxt.com/modules/supabase) module plugin: ``` export default defineNuxtConfig({ modules: [ "@nuxtjs/supabase", // ... ], // ... }); ``` and you create an instance of Supabase somewhere in your composables, e.g.: ``` const superbase = useSupabaseClient() ``` the test will fail due to: ``` ReferenceError: useSupabaseClient is not defined ``` Here, we recommend to either mock out the whole module that uses the `useSupabaseClient` function or create a global variable that mocks this function, e.g.: ``` import { fn } from '@wdio/browser-runner' globalThis.useSupabaseClient = fn().mockReturnValue({}) ``` --- Source: https://webdriver.io/docs/component-testing/svelte.md # Svelte [Svelte](https://svelte.dev/) is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app. You can test Svelte components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner.md#browser-runner). ## Setup[​](#setup "Direct link to Setup") To setup WebdriverIO within your Svelte project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. Make sure to select `svelte` as preset within your runner options, e.g.: ``` // wdio.conf.js export const config = { // ... runner: ['browser', { preset: 'svelte' }], // ... } ``` info If you are already using [Vite](https://vitejs.dev/) as development server you can also just re-use your configuration in `vite.config.ts` within your WebdriverIO config. For more information, see `viteConfig` in [runner options](/docs/runner.md#runner-options). The Svelte preset requires `@sveltejs/vite-plugin-svelte` to be installed. Also we recommend using [Testing Library](https://testing-library.com/) for rendering the component into the test page. Therefor you'll need to install the following additional dependencies: * npm * Yarn * pnpm * Bun ``` npm install --save-dev @testing-library/svelte @sveltejs/vite-plugin-svelte ``` ``` yarn add --dev @testing-library/svelte @sveltejs/vite-plugin-svelte ``` ``` pnpm add --save-dev @testing-library/svelte @sveltejs/vite-plugin-svelte ``` ``` bun add --dev @testing-library/svelte @sveltejs/vite-plugin-svelte ``` You can then start the tests by running: ``` npx wdio run ./wdio.conf.js ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following Svelte component: ./components/Component.svelte ```

Hello {name}!

``` In your test use the `render` method from `@testing-library/svelte` to attach the component to the test page. To interact with the component we recommend to use WebdriverIO commands as they behave more close to actual user interactions, e.g.: svelte.test.js ``` import expect from 'expect' import { render, fireEvent, screen } from '@testing-library/svelte' import '@testing-library/jest-dom' import Component from './components/Component.svelte' describe('Svelte Component Testing', () => { it('changes button text on click', async () => { render(Component, { name: 'World' }) const button = await $('button') await expect(button).toHaveText('Button') await button.click() await expect(button).toHaveText('Button Clicked') }) }) ``` You can find a full example of a WebdriverIO component test suite for Svelte in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/svelte-typescript-vite). --- Source: https://webdriver.io/docs/component-testing/solid.md # SolidJS [SolidJS](https://www.solidjs.com/) is a framework to build user interfaces with simple and performant reactivity. You can test SolidJS components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner.md#browser-runner). ## Setup[​](#setup "Direct link to Setup") To setup WebdriverIO within your SolidJS project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. Make sure to select `solid` as preset within your runner options, e.g.: ``` // wdio.conf.js export const config = { // ... runner: ['browser', { preset: 'solid' }], // ... } ``` info If you are already using [Vite](https://vitejs.dev/) as development server you can also just re-use your configuration in `vite.config.ts` within your WebdriverIO config. For more information, see `viteConfig` in [runner options](/docs/runner.md#runner-options). The SolidJS preset requires `vite-plugin-solid` to be installed: * npm * Yarn * pnpm * Bun ``` npm install --save-dev vite-plugin-solid ``` ``` yarn add --dev vite-plugin-solid ``` ``` pnpm add --save-dev vite-plugin-solid ``` ``` bun add --dev vite-plugin-solid ``` You can then start the tests by running: ``` npx wdio run ./wdio.conf.js ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following SolidJS component: ./components/Component.tsx ``` import { createSignal } from 'solid-js' function App() { const [theme, setTheme] = createSignal('light') const toggleTheme = () => { const nextTheme = theme() === 'light' ? 'dark' : 'light' setTheme(nextTheme) } return } export default App ``` In your test use the `render` method from `solid-js/web` to attach the component to the test page. To interact with the component we recommend to use WebdriverIO commands as they behave more close to actual user interactions, e.g.: app.test.tsx ``` import { expect } from '@wdio/globals' import { render } from 'solid-js/web' import App from './components/Component.jsx' describe('Solid Component Testing', () => { /** * ensure we render the component for every test in a * new root container */ let root: Element beforeEach(() => { if (root) { root.remove() } root = document.createElement('div') document.body.appendChild(root) }) it('Test theme button toggle', async () => { render(, root) const buttonEl = await $('button') await buttonEl.click() expect(buttonEl).toContainHTML('dark') }) }) ``` You can find a full example of a WebdriverIO component test suite for SolidJS in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/solidjs-typescript-vite). --- Source: https://webdriver.io/docs/component-testing/react.md # React [React](https://reactjs.org/) makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. You can test React components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner.md#browser-runner). ## Setup[​](#setup "Direct link to Setup") To setup WebdriverIO within your React project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. Make sure to select `react` as preset within your runner options, e.g.: ``` // wdio.conf.js export const config = { // ... runner: ['browser', { preset: 'react' }], // ... } ``` info If you are already using [Vite](https://vitejs.dev/) as development server you can also just re-use your configuration in `vite.config.ts` within your WebdriverIO config. For more information, see `viteConfig` in [runner options](/docs/runner.md#runner-options). The React preset requires `@vitejs/plugin-react` to be installed. Also we recommend using [Testing Library](https://testing-library.com/) for rendering the component into the test page. Therefor you'll need to install the following additional dependencies: * npm * Yarn * pnpm * Bun ``` npm install --save-dev @testing-library/react @vitejs/plugin-react ``` ``` yarn add --dev @testing-library/react @vitejs/plugin-react ``` ``` pnpm add --save-dev @testing-library/react @vitejs/plugin-react ``` ``` bun add --dev @testing-library/react @vitejs/plugin-react ``` You can then start the tests by running: ``` npx wdio run ./wdio.conf.js ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following React component: ./components/Component.jsx ``` import React, { useState } from 'react' function App() { const [theme, setTheme] = useState('light') const toggleTheme = () => { const nextTheme = theme === 'light' ? 'dark' : 'light' setTheme(nextTheme) } return } export default App ``` In your test use the `render` method from `@testing-library/react` to attach the component to the test page. To interact with the component we recommend to use WebdriverIO commands as they behave more close to actual user interactions, e.g.: app.test.tsx ``` import { expect } from '@wdio/globals' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import * as matchers from '@testing-library/jest-dom/matchers' expect.extend(matchers) import App from './components/Component.jsx' describe('React Component Testing', () => { it('Test theme button toggle', async () => { render() const buttonEl = screen.getByText(/Current theme/i) await $(buttonEl).click() expect(buttonEl).toContainHTML('dark') }) }) ``` You can find a full example of a WebdriverIO component test suite for React in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/react-typescript-vite). --- Source: https://webdriver.io/docs/component-testing/preact.md # Preact [Preact](https://preactjs.com/) is a fast 3kB alternative to React with the same modern API. You can test Preact components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner.md#browser-runner). ## Setup[​](#setup "Direct link to Setup") To setup WebdriverIO within your Preact project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. Make sure to select `preact` as preset within your runner options, e.g.: ``` // wdio.conf.js export const config = { // ... runner: ['browser', { preset: 'preact' }], // ... } ``` info If you are already using [Vite](https://vitejs.dev/) as development server you can also just re-use your configuration in `vite.config.ts` within your WebdriverIO config. For more information, see `viteConfig` in [runner options](/docs/runner.md#runner-options). The Preact preset requires `@preact/preset-vite` to be installed. Also we recommend using [Testing Library](https://testing-library.com/) for rendering the component into the test page. Therefor you'll need to install the following additional dependencies: * npm * Yarn * pnpm * Bun ``` npm install --save-dev @testing-library/preact @preact/preset-vite ``` ``` yarn add --dev @testing-library/preact @preact/preset-vite ``` ``` pnpm add --save-dev @testing-library/preact @preact/preset-vite ``` ``` bun add --dev @testing-library/preact @preact/preset-vite ``` You can then start the tests by running: ``` npx wdio run ./wdio.conf.js ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following Preact component: ./components/Component.jsx ``` import { h } from 'preact' import { useState } from 'preact/hooks' interface Props { initialCount: number } export function Counter({ initialCount }: Props) { const [count, setCount] = useState(initialCount) const increment = () => setCount(count + 1) return (
Current value: {count}
) } ``` In your test use the `render` method from `@testing-library/preact` to attach the component to the test page. To interact with the component we recommend to use WebdriverIO commands as they behave more close to actual user interactions, e.g.: app.test.tsx ``` import { expect } from 'expect' import { render, screen } from '@testing-library/preact' import { Counter } from './components/PreactComponent.js' describe('Preact Component Testing', () => { it('should increment after "Increment" button is clicked', async () => { const component = await $(render()) await expect(component).toHaveText(expect.stringContaining('Current value: 5')) const incrElem = await $(screen.getByText('Increment')) await incrElem.click() await expect(component).toHaveText(expect.stringContaining('Current value: 6')) }) }) ``` You can find a full example of a WebdriverIO component test suite for Preact in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/preact-typescript-vite). --- Source: https://webdriver.io/docs/component-testing/stencil.md # Stencil [Stencil](https://stenciljs.com/) is a library for building reusable, scalable component libraries. You can test Stencil components directly in a real browser using WebdriverIO and its [browser runner](/docs/runner.md#browser-runner). ## Setup[​](#setup "Direct link to Setup") To set up WebdriverIO within your Stencil project, follow the [instructions](/docs/component-testing.md#set-up) in our component testing docs. Make sure to select `stencil` as preset within your runner options, e.g.: ``` // wdio.conf.js export const config = { // ... runner: ['browser', { preset: 'stencil' }], // ... } ``` info In case you use Stencil with a framework like React or Vue, you should keep the preset for these frameworks. You can then start the tests by running: ``` npx wdio run ./wdio.conf.ts ``` ## Writing Tests[​](#writing-tests "Direct link to Writing Tests") Given you have the following Stencil components: ./components/Component.tsx ``` import { Component, Prop, h } from '@stencil/core' @Component({ tag: 'my-name', shadow: true }) export class MyName { @Prop() name: string normalize(name: string): string { if (name) { return name.slice(0, 1).toUpperCase() + name.slice(1).toLowerCase() } return '' } render() { return (

Hello! My name is {this.normalize(this.name)}.

) } } ``` ### `render`[​](#render "Direct link to render") In your test use the `render` method from `@wdio/browser-runner/stencil` to attach the component to the test page. To interact with the component we recommend using WebdriverIO commands as they behave closer to actual user interactions, e.g.: app.test.tsx ``` import { expect } from '@wdio/globals' import { render } from '@wdio/browser-runner/stencil' import MyNameComponent from './components/Component.tsx' describe('Stencil Component Testing', () => { it('should render component correctly', async () => { await render({ components: [MyNameComponent], template: () => ( ) }) await expect($('.text')).toHaveText('Hello! My name is Stencil.') }) }) ``` #### Render Options[​](#render-options "Direct link to Render Options") The `render` method provides the following options: ##### `components`[​](#components "Direct link to components") An array of components to test. Component classes can be imported into the spec file, then their reference should be added to the `component` array to be used throughout the test. **Type:** `CustomElementConstructor[]`
**Default:** `[]` ##### `flushQueue`[​](#flushqueue "Direct link to flushqueue") If `false`, do not flush the render queue on the initial test setup. **Type:** `boolean`
**Default:** `true` ##### `template`[​](#template "Direct link to template") The initial JSX that is used to generate the test. Use `template` when you want to initialize a component using their properties, instead of their HTML attributes. It will render the specified template (JSX) into `document.body`. **Type:** `JSX.Template` ##### `html`[​](#html "Direct link to html") The initial HTML used to generate the test. This can be useful to construct a collection of components working together, and assign HTML attributes. **Type:** `string` ##### `language`[​](#language "Direct link to language") Sets the mocked `lang` attribute on ``. **Type:** `string` ##### `autoApplyChanges`[​](#autoapplychanges "Direct link to autoapplychanges") By default, any changes to component properties and attributes must `env.waitForChanges()` to test the updates. As an option, `autoApplyChanges` continuously flushes the queue in the background. **Type:** `boolean`
**Default:** `false` ##### `attachStyles`[​](#attachstyles "Direct link to attachstyles") By default, styles are not attached to the DOM and they are not reflected in the serialized HTML. Setting this option to `true` will include the component's styles in the serializable output. **Type:** `boolean`
**Default:** `false` #### Render Environment[​](#render-environment "Direct link to Render Environment") The `render` method returns an environment object that provides certain utility helpers to manage the component's environment. ##### `flushAll`[​](#flushall "Direct link to flushall") After changes have been made to a component, such as an update to a property or attribute, the test page does not automatically apply the changes. To wait for, and apply the update, call `await flushAll()` **Type:** `() => void` ##### `unmount`[​](#unmount "Direct link to unmount") Removes the container element from the DOM. **Type:** `() => void` ##### `styles`[​](#styles "Direct link to styles") All styles defined by components. **Type:** `Record` ##### `container`[​](#container "Direct link to container") Container element in which the template is being rendered. **Type:** `HTMLElement` ##### `$container`[​](#container-1 "Direct link to container-1") The container element as a WebdriverIO element. **Type:** `WebdriverIO.Element` ##### `root`[​](#root "Direct link to root") The root component of the template. **Type:** `HTMLElement` ##### `$root`[​](#root-1 "Direct link to root-1") The root component as a WebdriverIO element. **Type:** `WebdriverIO.Element` ### `waitForChanges`[​](#waitforchanges "Direct link to waitforchanges") Helper method to wait for the component to be ready. ``` import { render, waitForChanges } from '@wdio/browser-runner/stencil' import { MyComponent } from './component.tsx' const page = render({ components: [MyComponent], html: '' }) expect(page.root.querySelector('div')).not.toBeDefined() await waitForChanges() expect(page.root.querySelector('div')).toBeDefined() ``` ## Element Updates[​](#element-updates "Direct link to Element Updates") If you define properties or states in your Stencil component you have to manage when these changes should be applied to the component to be re-rendered. ## Examples[​](#examples "Direct link to Examples") You can find a full example of a WebdriverIO component test suite for Stencil in our [example repository](https://github.com/webdriverio/component-testing-examples/tree/main/stencil-component-starter). --- Source: https://webdriver.io/docs/platforms/mobile.md # Mobile Apps WebdriverIO automates Android and iOS through [Appium](/docs/appium.md), which speaks the WebDriver protocol. Your tests use the same `browser` object (aliased as `driver`), `$`/`$$` selectors and `expect` matchers as browser tests. Appium routes each session to a platform driver chosen by `appium:automationName`. For Android that is `UiAutomator2`, with Espresso as an alternative that unlocks extra selector strategies. For iOS and iPadOS it is `XCUITest`. With these drivers you can test native apps and mobile web in Chrome on Android or Safari on iOS. You can also test hybrid apps, switching between the native context and embedded webviews. Sessions can run on Android emulators, iOS simulators, real devices, or device clouds such as Sauce Labs, BrowserStack, TestingBot and TestMu AI. The [`@wdio/appium-service`](/docs/appium-service.md) starts and stops a local Appium server for you. On top of the raw Appium API, WebdriverIO adds cross-platform [mobile commands](/docs/api/mobile.md) such as `tap`, `swipe`, `longPress`, `scrollIntoView` and `switchContext`. ## Quick start[​](#quick-start "Direct link to Quick start") Prerequisites: Android Studio with an Android SDK and an emulator for Android; Xcode and a simulator on macOS for iOS. `npx appium-installer` guides you through the environment setup, and `npm init wdio@latest .` scaffolds a mobile project (choose Android or iOS). To set up by hand: ``` npm install --save-dev @wdio/cli @wdio/local-runner @wdio/mocha-framework @wdio/spec-reporter @wdio/appium-service appium tsx npx appium driver install uiautomator2 # Android npx appium driver install xcuitest # iOS ``` tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types", "@wdio/mocha-framework"] } } ``` wdio.conf.ts ``` export const config: WebdriverIO.Config = { runner: 'local', port: 4723, specs: ['./test/specs/**/*.ts'], capabilities: [{ platformName: 'Android', 'appium:deviceName': 'Android GoogleAPI Emulator', 'appium:platformVersion': '12.0', 'appium:automationName': 'UiAutomator2', 'appium:app': './path/to/app.apk' }], services: ['appium'], logLevel: 'info', waitforTimeout: 10000, framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', timeout: 60000 } } ``` test/specs/app.e2e.ts ``` import { expect, driver, $ } from '@wdio/globals' describe('My app', () => { it('should open the contacts screen', async () => { await $('~Contacts').click() await expect($('~Add contact')).toBeDisplayed() }) it('should interact with a webview', async () => { await driver.switchContext({ title: 'My Webview Title' }) await expect($('h1')).toBeDisplayed() }) }) ``` ``` npx wdio run ./wdio.conf.ts ``` `~` is the accessibility id selector: it maps to `content-description` on Android and `accessibilityIdentifier` on iOS, and is the preferred cross-platform strategy. Replace the example ids, the webview title and the app path with your own. Other targets only change the capabilities: iOS simulator (native app) ``` { platformName: 'iOS', 'appium:deviceName': 'iPhone Simulator', 'appium:platformVersion': '16.4', 'appium:automationName': 'XCUITest', 'appium:app': './path/to/MyApp.app' // .app for simulators, signed .ipa for real devices } ``` Mobile web (Chrome on an Android emulator) ``` { platformName: 'Android', browserName: 'Chrome', 'appium:deviceName': 'Android GoogleAPI Emulator', 'appium:platformVersion': '12.0', 'appium:automationName': 'UiAutomator2' } ``` For iOS mobile web, use `platformName: 'iOS'`, `browserName: 'Safari'` and `'appium:automationName': 'XCUITest'`. ## Choose your path[​](#choose-your-path "Direct link to Choose your path") * [Appium Setup](/docs/appium.md): which platforms Appium covers (iOS, Android, Tizen, TV apps) and how to install the toolchain. * [Appium Service](/docs/appium-service.md): service options (`args`, `command`, `logPath`), `npx start-appium-inspector` to open the Appium Inspector, and a beta optimizer for slow XPath selectors. * [Mobile Commands](/docs/api/mobile.md): cross-platform gestures and helpers. Covers hybrid apps with [`getContexts`](/docs/api/mobile/getContexts.md) and [`switchContext`](/docs/api/mobile/switchContext.md), plus the webview capabilities for iOS. * [Mobile Selectors](/docs/selectors.md#mobile-selectors): accessibility id, Android UiAutomator, Espresso data/view matchers and iOS predicate strings and class chains. * [Appium protocol commands](/docs/api/appium.md): the raw Appium endpoints available on `driver`. * [Flutter apps](/docs/flutter-testing/introduction.md): why Flutter needs the Appium Flutter Driver, then [prepare the app](/docs/flutter-testing/preparing-flutter-application.md), [configure Appium](/docs/flutter-testing/base-appium-configuration.md), [set up WebdriverIO](/docs/flutter-testing/setting-up-webdriverio.md) and [write tests](/docs/flutter-testing/writing-tests.md). * [Cloud Services](/docs/cloudservices.md): connect to Sauce Labs, BrowserStack, TestingBot, TestMu AI, Perfecto or RobotActions to run on hosted real devices. * [Visual Testing](/docs/visual-testing.md): image comparison for native apps, hybrid apps and mobile browsers. For Percy on mobile, see [App Percy](/docs/visual-testing/integrate-with-app-percy.md). * [Multi-remote](/docs/multiremote.md): coordinate several devices or browsers in one test. Emulating a device viewport in a desktop browser with [`browser.emulate('device', ...)`](/docs/emulation.md) is not mobile testing. Desktop browser engines differ from mobile ones, so use Appium with a real mobile browser instead. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") * Session doesn't start: make sure the Appium driver for your `appium:automationName` is installed and the emulator or simulator is running. Use `port: 4723` unless you changed the Appium port. * iOS can't find a webview: try `appium:webviewConnectRetries`, `appium:webviewConnectTimeout` or `appium:includeSafariInWebviews` (see [Hybrid Apps](/docs/api/mobile.md#hybrid-apps)). * Android webview is slow to appear: tune `androidWebviewConnectionRetryTime` and `androidWebviewConnectTimeout` on `getContexts`/`switchContext`. * Flutter widgets aren't found with native selectors: that's expected. Use the Flutter driver and finders described in the [Flutter guide](/docs/flutter-testing/introduction.md). ## Next steps[​](#next-steps "Direct link to Next steps") * [Configuration](/docs/configuration.md) and [Capabilities](/docs/capabilities.md) references. * [Page Object Pattern](/docs/pageobjects.md) to share screens between Android and iOS specs. * [MCP](/docs/mcp.md) to let an AI agent drive iOS and Android sessions through Appium. * Other platforms: [Web Browsers](/docs/platforms/web.md), [Desktop Apps](/docs/platforms/desktop.md), [Extensions & Editors](/docs/platforms/apps-and-extensions.md). --- Source: https://webdriver.io/docs/appium.md # Appium Setup With WebdriverIO you can test not only web application in the browser but also other platforms such as: * 📱 mobile applications on iOS, Android or Tizen * 🖥️ desktop applications on macOS or Windows * 📺 as well as TV apps for Roku, tvOS, Android TV and Samsung We recommend to use [Appium](https://appium.io/) to help you facilitate these types of tests. You can get an overview on Appium on their [official documentation page](https://appium.io/docs/en/latest/intro/). Setting up the right environment is not straight forward. Luckily the Appium ecosystem has great tooling around this to help you. To set-up one of the above environments, just run: ``` $ npx appium-installer ``` This will initiate the [appium-installer](https://github.com/AppiumTestDistribution/appium-installer) toolkit that guides you through the setup process. --- Source: https://webdriver.io/docs/flutter-testing/introduction.md # Introduction This guide covers configuring, structuring, and running End-to-End (E2E) tests for **Flutter** applications using **WebdriverIO** and **Appium**. WebdriverIO provides a Node.js-based test framework with native support for the WebDriver and Appium protocols, allowing you to automate Flutter applications across both Android and iOS. *** ### The Architectural Challenge: Why Flutter is Different[​](#the-architectural-challenge-why-flutter-is-different "Direct link to The Architectural Challenge: Why Flutter is Different") When automating standard native mobile apps (Kotlin/Java on Android or Swift/Objective-C on iOS), Appium drivers (`UiAutomator2` for Android, `XCUITest` for iOS) act as the access point for inspecting and interacting with the application by querying the operating system's native accessibility tree. These drivers read OS-level UI components (buttons, inputs, labels) and expose them to inspection tools and test scripts using standard locator strategies such as ID, Accessibility ID, or XPath. Flutter works differently: Flutter does not use the operating system's native UI components. Instead, it renders its UI directly onto a canvas rendered via an internally hosted graphics engine. The framework draws its own widgets pixel by pixel. #### Impact on Traditional Automation[​](#impact-on-traditional-automation "Direct link to Impact on Traditional Automation") For standard native drivers and inspectors, a Flutter app often appears as a single graphic surface. Internal widgets (such as buttons or text fields) do not exist in the OS accessibility tree by default. As a result, standard native locator strategies cannot interact directly with internal Flutter widgets. *** ### How WebdriverIO and Appium Handle Flutter[​](#how-webdriverio-and-appium-handle-flutter "Direct link to How WebdriverIO and Appium Handle Flutter") WebdriverIO and Appium provide the tooling required to interact with Flutter's internal widget tree, but you need to install and configure the appropriate driver and locator extensions for your project. By using the [Appium Flutter Driver](https://github.com/appium/appium-flutter-driver), Appium connects to Flutter's test extension (`flutter_driver`). This gives you access to Flutter-specific locator strategies (Finders), including: * `byValueKey`: Locates widgets by their explicit `Key` in Flutter code. * `byText`: Locates widgets by visible text content. * `byTooltip`: Locates widgets by their tooltip text. The following sections walk through the prerequisites, environment setup, and writing your first test suite. --- Source: https://webdriver.io/docs/flutter-testing/preparing-flutter-application.md # Preparing the Flutter App For WebdriverIO and Appium to inspect and interact with internal elements inside the Flutter canvas, the application must expose a communication channel. This is achieved by enabling Flutter's test extension in the application's source code. Sharing with Development Teams Automation engineers (QAs) often do not have direct access to the Flutter app codebase. If you do not maintain the app code yourself, share this page with your development team so they can add the `flutter_driver` extension and provide a test build (`.apk`, `.app`, or `.ipa`). Legacy Extension Flutter's recommended testing path for newer apps is the `integration_test` package. However, the Appium Flutter Driver integrates with the legacy `flutter_driver` extension, which is why this guide uses `enableFlutterDriverExtension()`. ### Configuring `pubspec.yaml`[​](#configuring-pubspecyaml "Direct link to configuring-pubspecyaml") Add `flutter_driver` under `dev_dependencies` in your Flutter project's `pubspec.yaml` file: ``` dev_dependencies: flutter_test: sdk: flutter flutter_driver: sdk: flutter ``` Fetch the dependencies: ``` flutter pub get ``` ### Enabling the Extension in `main.dart`[​](#enabling-the-extension-in-maindart "Direct link to enabling-the-extension-in-maindart") To start the instrumentation server that responds to commands from WebdriverIO, invoke `enableFlutterDriverExtension()` before `runApp`: ``` import 'package:flutter/material.dart'; import 'package:flutter_driver/driver_extension.dart'; void main() { // Enable the Flutter driver extension before starting the app enableFlutterDriverExtension(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('E2E Testing Flutter')), body: const Center(child: Text('Application ready for automation!')), ), ); } } ``` Best Practice: Separate Test Entry Point To prevent test instrumentation code from entering production builds, create a separate entry point file (such as `lib/main_e2e.dart`) that enables the extension and calls the main app. This keeps production builds clean and secure: ``` import 'package:flutter_driver/driver_extension.dart'; import 'main.dart' as app; void main() { enableFlutterDriverExtension(); app.main(); } ``` ### Official Reference Documentation[​](#official-reference-documentation "Direct link to Official Reference Documentation") To learn more about component exposure mechanics and `enableFlutterDriverExtension()`, refer to the official [Flutter API Reference](https://api.flutter.dev/flutter/flutter_driver_extension/enableFlutterDriverExtension.html) and Flutter's [Integration Testing Guide](https://docs.flutter.dev/testing/integration-tests). --- Source: https://webdriver.io/docs/flutter-testing/base-appium-configuration.md # Base Appium Configuration WebdriverIO uses Appium to run tests across mobile emulators, simulators, and real devices. The `@wdio/appium-service` automatically manages the Appium server lifecycle during test execution. For general Appium setup and capability options, see the [Appium Service Documentation](https://webdriver.io/docs/appium-service/). ## Installing Dependencies[​](#installing-dependencies "Direct link to Installing Dependencies") To test Flutter applications, install the Appium service and the Flutter finder package: ``` npm install --save-dev @wdio/appium-service appium appium-flutter-finder ``` ### Installing the Appium Flutter Driver[​](#installing-the-appium-flutter-driver "Direct link to Installing the Appium Flutter Driver") You can install the Appium Flutter Driver (`appium-flutter-driver`) in one of two ways: #### Option 1: As a Dev Dependency (Recommended for CI/CD)[​](#option-1-as-a-dev-dependency-recommended-for-cicd "Direct link to Option 1: As a Dev Dependency (Recommended for CI/CD)") Adding the driver directly to your `devDependencies` ensures that all team members and CI/CD pipelines have the driver installed automatically without requiring extra setup steps: ``` npm install --save-dev appium-flutter-driver ``` > You can also install all required packages together in a single command: > > ``` > npm install --save-dev @wdio/appium-service appium appium-flutter-finder appium-flutter-driver > ``` #### Option 2: Via Appium CLI (Local Setup)[​](#option-2-via-appium-cli-local-setup "Direct link to Option 2: Via Appium CLI (Local Setup)") Alternatively, you can install the driver locally into your Appium environment using the Appium CLI: ``` npx appium driver install flutter ``` ### Package Overview[​](#package-overview "Direct link to Package Overview") These packages provide: * **`@wdio/appium-service` & `appium`**: Starts and manages the Appium server during test runs. * **`appium-flutter-driver`**: The Appium driver responsible for communicating with Flutter's test extension. * **`appium-flutter-finder`**: Helper library providing Flutter-specific locator strategies (`byValueKey`, `byText`, `byTooltip`). --- Source: https://webdriver.io/docs/flutter-testing/setting-up-webdriverio.md # Setting up WebdriverIO in your environment The `wdio.conf.ts` file is the core configuration file of any WebdriverIO project. This is where you define where tests run, which test frameworks to use, and the necessary `capabilities` for Appium to correctly initialize the Flutter application. warning The `appium-flutter-driver` operates differently from traditional native drivers (such as `UiAutomator2` or `XCUITest`). It communicates with Flutter's test extension (`flutter_driver`) through a customized protocol. Because of this, standard native automation commands might not work the same way or may strictly require using `appium-flutter-finder`. To fully understand the limitations, supported commands, and protocol extensions, refer to the tool's official repository: [Appium Flutter Driver on GitHub](https://github.com/appium/appium-flutter-driver). ### Capabilities Configuration (Android & iOS)[​](#capabilities-configuration-android--ios "Direct link to Capabilities Configuration (Android & iOS)") ``` export const config: WebdriverIO.Config = { // ... other wdio.conf.ts configurations (runner, specs, etc.) services: [ ['appium', { // WebdriverIO manages the Appium server lifecycle args: {}, command: 'appium' }] ], capabilities: [ // ========================================== // ANDROID CONFIGURATION // ========================================== { 'platformName': 'Android', 'appium:automationName': 'Flutter', // Sets the mandatory use of the Flutter driver 'appium:deviceName': 'Android_Emulator', // Name of your configured emulator or real device // PATH OBSERVATION (See Operating Systems note below) 'appium:app': './build/app/outputs/flutter-apk/app-debug.apk', 'appium:autoGrantPermissions': true }, // ========================================== // IOS CONFIGURATION (Requires macOS) // ========================================== { 'platformName': 'iOS', 'appium:automationName': 'Flutter', // Sets the mandatory use of the Flutter driver 'appium:deviceName': 'iPhone Simulator', // Name of the iOS simulator or real device 'appium:platformVersion': '17.2', // Change to your target OS version // PATH OBSERVATION (See Operating Systems note below) // Use .app for iOS Simulator, or .ipa for real iOS devices 'appium:app': './ios/build/Build/Products/Debug-iphonesimulator/Runner.app', 'appium:noReset': false } ], // ... rest of configuration }; ``` ### Important Observations on File Paths (appium:app)[​](#important-observations-on-file-paths-appium "Direct link to important-observations-on-file-paths-appium") Defining the binary application path (`.apk` for Android, `.app` or `.ipa` for iOS) inside the `appium:app` property requires careful attention depending on the operating system and target environment: * **On Windows**: The operating system uses backslashes (`\`) for directory paths. When mapping the path to your `.apk` file on Windows, ensure you escape the backslashes in your configuration file (e.g., `.\\build\\app\\outputs\\flutter-apk\\app-debug.apk`) or use consistent forward slashes (`/`), which are correctly parsed by Node.js. * **On macOS / Linux**: Standard paths with forward slashes (`/`) are used. Remember that iOS builds (`.app` for Simulator or `.ipa` for real devices) can only be compiled within macOS environments. * **iOS Simulator vs Real Devices**: Use `.app` bundles when executing against the iOS Simulator and signed `.ipa` packages when running against physical iOS devices. * **Absolute vs Relative Paths**: It is highly recommended to use relative paths starting from the project root (using `./`) to guarantee portability across different development machines and Continuous Integration (CI) environments. --- Source: https://webdriver.io/docs/flutter-testing/writing-tests.md # Writing Tests This section covers the practical structure for creating automated test scenarios, how to interact directly with Flutter's internal component tree using WebdriverIO. ### Why is Context Switching Necessary?[​](#why-is-context-switching-necessary "Direct link to Why is Context Switching Necessary?") When initiating an automation session with Appium, the driver begins execution by mapping the native context of the operating system, known as `NATIVE_APP`. This context can only see the native shell wrapping the application (such as the system status bar or native Android/iOS dialogs). Since Flutter renders its user interface inside an isolated Canvas, internal elements are invisible within the `NATIVE_APP` context. To send commands directly to Flutter's test extension (`flutter_driver`), we must explicitly switch the automation focus to the `FLUTTER` context. Without this switch, any attempt to locate a Widget will result in an element not found error. Best Practice: Always Switch Context in `beforeEach` It is a recommended best practice to include `await driver.switchContext('FLUTTER')` in a `beforeEach` hook in every test file. This ensures that every test begins execution in the `FLUTTER` context, avoiding flakiness or state leakage if a previous test switched to `NATIVE_APP` (e.g., to handle OS permission dialogs) or if a session resets the active context. ### Why is `appium-flutter-finder` Necessary?[​](#why-is-appium-flutter-finder-necessary "Direct link to why-is-appium-flutter-finder-necessary") Traditional WebdriverIO selectors, like `$('~selector')` or `$('#id')`, are designed to locate elements using strategies intended for Web or mobile native interfaces (such as resource IDs or XPath). Flutter manages its own internal elements and uses proprietary search methods (such as `byValueKey`, `byText`, `byType`). The `appium-flutter-finder` library is required because it acts as a translator: it exposes these Flutter-specific locator strategies into a serialized format (Base64/JSON) that the `appium-flutter-driver` can interpret and execute inside the Dart Virtual Machine (VM). ### Practical Test Examples[​](#practical-test-examples "Direct link to Practical Test Examples") We document common scenarios using `appium-flutter-finder` to locate widgets, combined with direct extension commands executed through `driver.execute('flutter:')`. Flutter Driver Extension Commands & Finders The `appium-flutter-driver` provides specialized commands for interacting with Flutter applications, including: * `flutter:waitFor`: Waits for a widget to become visible. * `flutter:waitForAbsent`: Waits for a widget to disappear. * `flutter:scroll` / `flutter:scrollIntoView` / `flutter:scrollUntilVisible`: Handles scrolling within scrollable views. * `flutter:setTextEntryEmulation`: Configures text input behavior. For the full list of available commands, parameters, and return types, see the [Appium Flutter Driver Commands Documentation](https://github.com/appium/appium-flutter-driver#commands), the [Node.js Finder source code](https://github.com/appium/appium-flutter-driver/tree/main/finder/nodejs), and the [appium-flutter-finder on npm](https://www.npmjs.com/package/appium-flutter-finder). ### Example A — Simple interaction (Counter flow)[​](#example-a--simple-interaction-counter-flow "Direct link to Example A — Simple interaction (Counter flow)") ``` // counter.spec.ts import find from 'appium-flutter-finder'; describe('Flutter Counter Flow', () => { beforeEach(async () => { await driver.switchContext('FLUTTER'); }); it('The counter should be successfully incremented by clicking the button.', async () => { const incrementButton = find.byTooltip('Increment'); const counterText = find.byValueKey('counter_text'); const initialValue = await driver.getElementText(counterText); expect(initialValue).toBe('0'); await driver.elementClick(incrementButton); const finalValue = await driver.getElementText(counterText); expect(finalValue).toBe('1'); }); }); ``` ### Example B — Stable Navigation (Avoiding Timeouts)[​](#example-b--stable-navigation-avoiding-timeouts "Direct link to Example B — Stable Navigation (Avoiding Timeouts)") ``` // redirects.spec.ts import find from 'appium-flutter-finder'; describe('Flutter Redirects Flow', () => { beforeEach(async () => { await driver.switchContext('FLUTTER'); }); it('The user should be able to navigate between the Redirect Example views and back to the first view.', async () => { const buttonGoToRedirectExampleTwoView = find.byValueKey('redirect_example_two_button'); await driver.elementClick(buttonGoToRedirectExampleTwoView); const redirectExampleTwoBody = find.byValueKey('redirect_example_two_body'); await driver.execute('flutter:waitFor', redirectExampleTwoBody); const textRedirectExampleTwoBody = await driver.getElementText(redirectExampleTwoBody); expect(textRedirectExampleTwoBody).toBe('This is the Redirect Example Two View'); const buttonGoBackToRedirectExampleView = find.byValueKey('redirect_example_two_back_button'); await driver.elementClick(buttonGoBackToRedirectExampleView); const redirectExampleBody = find.byValueKey('redirect_example_body'); await driver.execute('flutter:waitFor', redirectExampleBody); const textRedirectExampleBody = await driver.getElementText(redirectExampleBody); expect(textRedirectExampleBody).toBe('This is the Redirect Example View'); }); }); ``` ### Example C — Switching Contexts (Native OS Dialogs & Permissions)[​](#example-c--switching-contexts-native-os-dialogs--permissions "Direct link to Example C — Switching Contexts (Native OS Dialogs & Permissions)") ``` // native_dialog_context.spec.ts import find from 'appium-flutter-finder'; describe('Flutter & Native Context Switching Flow', () => { beforeEach(async () => { await driver.switchContext('FLUTTER'); }); it('The user should trigger a native dialog, interact with OS controls, and return to Flutter context.', async () => { // 1. In FLUTTER context: click widget that triggers an OS-level permission or alert dialog const buttonRequestPermission = find.byValueKey('request_permission_button'); await driver.elementClick(buttonRequestPermission); // 2. Switch to NATIVE_APP context to interact with the OS dialog await driver.switchContext('NATIVE_APP'); // Locate and click native button using standard WebdriverIO selectors const nativeAllowButton = await $('//*[@text="Allow" or @text="While using the app" or @label="Allow"]'); await nativeAllowButton.waitForDisplayed(); await nativeAllowButton.click(); // 3. Switch back to FLUTTER context to continue verifying Flutter widgets await driver.switchContext('FLUTTER'); const permissionStatusText = find.byValueKey('permission_status_text'); await driver.execute('flutter:waitFor', permissionStatusText); const status = await driver.getElementText(permissionStatusText); expect(status).toBe('Permission Granted'); }); }); ``` ## Build and Execution Flow[​](#build-and-execution-flow "Direct link to Build and Execution Flow") To ensure your recent Dart code and Key changes are visible to the tests, always follow these steps: ``` flutter build apk -t lib/main_e2e.dart --debug npx wdio run wdio.conf.ts ``` You can see the code examples in the repository: --- Source: https://webdriver.io/docs/platforms/desktop.md # Desktop Apps How WebdriverIO automates a desktop app depends on how the app is built. Native macOS apps are automated through [Appium](/docs/appium.md) with the Mac2 driver (`'appium:automationName': 'Mac2'`), which requires Xcode. Apps built with a web-based framework are driven through their embedded browser engine by a dedicated WebdriverIO service. The [Electron service](/docs/desktop-testing/electron.md) uses Chromium via an auto-installed Chromedriver and can also call Electron main-process APIs. The [Tauri service](/docs/desktop-testing/tauri.md) and the [Dioxus service](/docs/desktop-testing/dioxus.md) drive the operating system webview: WebView2 on Windows, WKWebView on macOS and WebKitGTK on Linux. These three services run the same suite on Windows, macOS and Linux. Native Windows apps have no recommended driver today: Appium's Windows Driver is built on Microsoft's WinAppDriver, which is no longer maintained. There is no documented support for automating arbitrary native Linux apps. | App type | macOS | Windows | Linux | How | | ---------- | ----- | --------------- | -------------- | ------------------------------------------------------------------------- | | Native app | Yes | Not recommended | Not documented | Appium Mac2 driver | | Electron | Yes | Yes | Yes | `@wdio/electron-service` (Chromedriver) | | Tauri | Yes | Yes | Yes | `@wdio/tauri-service` (embedded plugin, `tauri-driver` or CrabNebula) | | Dioxus | Yes | Yes | Yes | `@wdio/dioxus-service` (embedded driver; external driver on Windows only) | ## Quick start[​](#quick-start "Direct link to Quick start") `npm create wdio@latest ./` scaffolds all of these. Choose "Desktop Testing - of Electron, Tauri, Dioxus, or macOS Applications" and then your framework. Every setup below also needs `@wdio/cli @wdio/local-runner @wdio/mocha-framework @wdio/spec-reporter tsx` and a `tsconfig.json` with `"types": ["node", "@wdio/globals/types", "@wdio/mocha-framework"]`. ### Electron (macOS, Windows, Linux)[​](#electron-macos-windows-linux "Direct link to Electron (macOS, Windows, Linux)") ``` npm install --save-dev @wdio/electron-service ``` wdio.conf.ts ``` /// export const config: WebdriverIO.Config = { runner: 'local', specs: ['./test/specs/**/*.ts'], capabilities: [{ browserName: 'electron', 'wdio:electronServiceOptions': { // only needed if auto-detection of Electron Forge / electron-builder output fails // appBinaryPath: './dist-electron/linux-unpacked/myApp', appArgs: [] } }], services: ['electron'], framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', timeout: 60000 } } ``` test/specs/app.e2e.ts ``` import { browser } from '@wdio/globals' describe('Electron Testing', () => { it('should print application title', async () => { console.log('Hello', await browser.getTitle(), 'application!') }) }) ``` Use `browser.electron.execute((electron, ...args) => { ... })` to run code in the main process, and `browser.electron.mock()` to mock Electron APIs. ### Native macOS app (Appium Mac2)[​](#native-macos-app-appium-mac2 "Direct link to Native macOS app (Appium Mac2)") ``` npm install --save-dev @wdio/appium-service appium appium-mac2-driver ``` wdio.conf.ts ``` export const config: WebdriverIO.Config = { runner: 'local', port: 4723, specs: ['./test/specs/**/*.ts'], capabilities: [{ platformName: 'Mac', 'appium:automationName': 'Mac2', 'appium:bundleId': 'com.apple.calculator' }], services: ['appium'], framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', timeout: 60000 } } ``` test/specs/calculator.e2e.ts ``` import { expect, $ } from '@wdio/globals' describe('MacOS Testing', () => { it('should calculate the meaning of life', async function () { await $('//XCUIElementTypeButton[@label="seven"]').click() await $('//XCUIElementTypeButton[@label="multiply"]').click() await $('//XCUIElementTypeButton[@label="six"]').click() await $('//XCUIElementTypeButton[@title="="]').click() await expect($('//XCUIElementTypeStaticText[@label="main display"]')).toHaveText('42') }) }) ``` `appium:bundleId` selects the app to launch at session start. ### Tauri and Dioxus[​](#tauri-and-dioxus "Direct link to Tauri and Dioxus") Both need a Rust-side addition to your app, so follow their quick starts: * Tauri: add the `tauri-plugin-wdio-webdriver` crate (the embedded provider), then use `services: [['tauri', { appBinaryPath: './src-tauri/target/release/my-tauri-app', driverProvider: 'embedded' }]]`. See the [Tauri Quick Start](/docs/desktop-testing/tauri/quick-start.md). * Dioxus: add the `wdio-dioxus-bridge` crate and create a debug build (`cargo build`). Then use `services: [['dioxus', { driverProvider: 'embedded' }]]` with `browserName: 'dioxus'` and `'dioxus:options': { application: './target/debug/my-app' }`. See the [Dioxus Quick Start](/docs/desktop-testing/dioxus/quick-start.md). ## Choose your path[​](#choose-your-path "Direct link to Choose your path") * [macOS](/docs/desktop-testing/macos.md): native macOS apps with Appium and the Mac2 driver. * [Windows](/docs/desktop-testing/windows.md): current state of native Windows app automation. * [Electron](/docs/desktop-testing/electron.md): setup, then [configuration](/docs/desktop-testing/electron/configuration.md) (including binary paths per OS), [accessing Electron APIs](/docs/desktop-testing/electron/api.md), [API reference and mocking](/docs/desktop-testing/electron/api-reference.md), [window management](/docs/desktop-testing/electron/window-management.md), [deeplinks](/docs/desktop-testing/electron/deeplink-testing.md), [standalone mode](/docs/desktop-testing/electron/standalone.md) and [debugging](/docs/desktop-testing/electron/debugging.md). * [Tauri](/docs/desktop-testing/tauri.md): [platform support](/docs/desktop-testing/tauri/platform-support.md), [configuration](/docs/desktop-testing/tauri/configuration.md), [plugin setup](/docs/desktop-testing/tauri/plugin-setup.md), [CrabNebula](/docs/desktop-testing/tauri/crabnebula-setup.md), [Edge WebDriver on Windows](/docs/desktop-testing/tauri/edge-webdriver-windows.md), [usage examples](/docs/desktop-testing/tauri/usage-examples.md) and the [API reference](/docs/desktop-testing/tauri/api.md). * [Dioxus](/docs/desktop-testing/dioxus.md): [platform support](/docs/desktop-testing/dioxus/platform-support.md), [configuration](/docs/desktop-testing/dioxus/configuration.md), [bridge setup](/docs/desktop-testing/dioxus/plugin-setup.md), [browser mode](/docs/desktop-testing/dioxus/browser-mode.md) (frontend-only tests in Chrome with mocked commands), [usage examples](/docs/desktop-testing/dioxus/usage-examples.md) and the [API reference](/docs/desktop-testing/dioxus/api.md). * [Multi-remote](/docs/multiremote.md): the Electron, Tauri and Dioxus services support multi-remote sessions, e.g. two app instances in one test. ## Linux[​](#linux "Direct link to Linux") On Linux, WebdriverIO drives Electron, Tauri and Dioxus apps. Things to know: * Headless CI: these apps need a display server. When no display exists, the testrunner starts Weston, or Xvfb as a fallback. Set `displayServerAutoInstall: true` to install one if neither is installed. Alternatively, wrap the testrunner with xvfb-run, e.g. `xvfb-run -a npx wdio run wdio.conf.ts`. See [Headless & Display Servers](/docs/headless-and-display-servers.md). * Tauri with the `official` provider needs WebKitWebDriver (`webkit2gtk-driver` package). The `embedded` provider needs no external driver. * Dioxus supports only the `embedded` provider on Linux, and building Dioxus apps requires the WebKitGTK development libraries. * Electron on Ubuntu 24.04+ and other AppArmor-enabled distributions: set the service option `apparmorAutoInstall` if Electron fails to start. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") * Electron: [Common Issues](/docs/desktop-testing/electron/common-issues.md), e.g. "DevToolsActivePort file doesn't exist" in CI. * Tauri: [Troubleshooting](/docs/desktop-testing/tauri/troubleshooting.md), including Edge WebDriver and WebView2 version mismatches. * Dioxus: [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md). * macOS: see the [Appium Mac2 Driver](https://appium.github.io/appium-mac2-driver/) project for driver-specific setup such as Xcode. ## Next steps[​](#next-steps "Direct link to Next steps") * [Configuration](/docs/configuration.md) reference for every `wdio.conf.ts` option. * [Appium Service](/docs/appium-service.md) options for the Mac2 setup. * Other platforms: [Web Browsers](/docs/platforms/web.md), [Mobile Apps](/docs/platforms/mobile.md), [Extensions & Editors](/docs/platforms/apps-and-extensions.md). --- Source: https://webdriver.io/docs/desktop-testing/macos.md # MacOS WebdriverIO can automate arbitrary MacOS application using [Appium](https://appium.io/). All you need is [XCode](https://developer.apple.com/xcode/) installed on your system, Appium and the [Mac2 Driver](https://appium.github.io/appium-mac2-driver/) installed as dependency and the correct capabilities set. ## Getting Started[​](#getting-started "Direct link to Getting Started") To initiate a new WebdriverIO project, run: ``` npm create wdio@latest ./ ``` An installation wizard will guide you through the process. Ensure you select *"Desktop Testing - of MacOS Applications"* when it asks you what type of testing you'ld like to do. Afterwards just keep the defaults or modify based on your preference. The configuration wizard will install all required Appium packages and creates a `wdio.conf.js` or `wdio.conf.ts` with the necessary configuration to test on MacOS. If you agreed to autogenerate some tests files you can run your first test via `npm run wdio`. That's it 🎉 ## Example[​](#example "Direct link to Example") This is how a simple test can look like that opens the Calculator application, makes a calculation and verifies its result: ``` describe('My Login application', () => { it('should set a text to a text view', async function () { await $('//XCUIElementTypeButton[@label="seven"]').click() await $('//XCUIElementTypeButton[@label="multiply"]').click() await $('//XCUIElementTypeButton[@label="six"]').click() await $('//XCUIElementTypeButton[@title="="]').click() await expect($('//XCUIElementTypeStaticText[@label="main display"]')).toHaveText('42') }); }) ``` **Note:** the calculator app was opened automatically at the beginning of the session because `'appium:bundleId': 'com.apple.calculator'` was defined as capability option. You can switch apps during the session at all times. ## More Information[​](#more-information "Direct link to More Information") For information about specifics around testing on MacOS we recommend to go checkout the [Appium Mac2 Driver](https://appium.github.io/appium-mac2-driver/) project. --- Source: https://webdriver.io/docs/desktop-testing/windows.md # Windows Unfortunately there is at the moment no stable driver for automating Windows applications. Even though Appium maintains a [Windows Driver](https://github.com/appium/appium-windows-driver) that is based on Microsoft's [WinAppDriver server](https://github.com/microsoft/WinAppDriver), we would not recommend using it given that Microsoft has stopped maintaining the server and there are a lot of [known bugs](https://github.com/search?q=repo%3Amicrosoft%2FWinAppDriver+webdriverio\&type=issues). If anyone is aware of a way to automate Windows applications, please let us know on [Discord](https://discord.webdriver.io). --- Source: https://webdriver.io/docs/desktop-testing/electron.md # Electron Electron is a framework for building desktop applications using JavaScript, HTML, and CSS. By embedding Chromium and Node.js into its binary, Electron allows you to maintain one JavaScript codebase and create cross-platform apps that work on Windows, macOS, and Linux — no native development experience is required. WebdriverIO provides an integrated service that simplifies the interaction with your Electron app and makes testing it very simple. The advantages of using WebdriverIO for testing Electron applications are: * 🚗 auto-setup of required Chromedriver * 📦 automatic path detection of your Electron application - supports [Electron Forge](https://www.electronforge.io/) and [Electron Builder](https://www.electron.build/) * 🧩 access Electron APIs within your tests * 🕵️ mocking of Electron APIs via a Vitest-like API You just need a few simple steps to get started. Watch this simple step-by-step getting started video tutorial from the [WebdriverIO YouTube](https://www.youtube.com/@webdriverio) channel: Or follow the guide in the following section. ## Getting Started[​](#getting-started "Direct link to Getting Started") To initiate a new WebdriverIO project, run: ``` npm create wdio@latest ./ ``` An installation wizard will guide you through the process. When asked what type of testing you'd like to do, select *"Desktop Testing - of Electron, Tauri, or macOS Applications"*, then choose *Electron* at the framework prompt. Afterwards provide the path to your compiled Electron application, e.g. `./dist`, then just keep the defaults or modify based on your preference. The configuration wizard will install all required packages and create a `wdio.conf.js` or `wdio.conf.ts` with the necessary configuration to test your application. If you agree to autogenerate some test files you can run your first test via `npm run wdio`. ## Manual Setup[​](#manual-setup "Direct link to Manual Setup") If you are already using WebdriverIO in your project you can skip the installation wizard and just add the following dependencies: ``` npm install --save-dev @wdio/electron-service ``` Then you can use the following configuration: ``` // wdio.conf.ts export const config: WebdriverIO.Config = { // ... services: [['electron', { appEntryPoint: './path/to/bundled/electron/main.bundle.js', appArgs: [/** ... */], }]] } ``` That's it 🎉 Learn more about how [to configure the Electron Service](/docs/desktop-testing/electron/configuration.md), [how to mock Electron APIs](/docs/desktop-testing/electron/api-reference.md) and [how to access Electron APIs](/docs/desktop-testing/electron/api.md). --- Source: https://webdriver.io/docs/desktop-testing/electron/configuration.md # Configuration This document covers all configuration options for the WDIO Electron Service, including service options and Chromedriver configuration. ## Service Configuration[​](#service-configuration "Direct link to Service Configuration") The service can be configured by setting `wdio:electronServiceOptions` either on the service level or capability level, in which capability level configurations take precedence, e.g. the following WebdriverIO configuration: *`wdio.conf.ts`* ``` export const config = { // ... services: [ [ 'electron', { appBinaryPath: '/foo/bar/myApp' }, ], ], capabilities: [ { 'browserName': 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/foo/bar/myOtherApp' appArgs: ['foo', 'bar'], }, }, ], // ... }; ``` ...would result in the following configuration object: ``` { "appBinaryPath": "/foo/bar/myOtherApp", "appArgs": ["foo", "bar"] } ``` ## Service Options[​](#service-options "Direct link to Service Options") The service supports the following configuration options: ### `appArgs`:[​](#appargs "Direct link to appargs") * Type `string[]` An array of string arguments to be passed through to the app on execution of the test run. Electron [command line switches](https://www.electronjs.org/docs/latest/api/command-line-switches) and some [Chromium switches](https://peter.sh/experiments/chromium-command-line-switches) can be used here. ### `appBinaryPath`:[​](#appbinarypath "Direct link to appbinarypath") * Type `string` The path to the Electron binary of the app for testing. In most cases the service will determine the path to your app automatically [(check here)](#automatic-detection-of-app-binary), but if this fails for some reason, e.g. your app is in a different repository from your tests, then it is recommended to set this value manually. If you manually set the path to the Electron binary, the path will be in different formats depending on the build tool you are using, how that tool is configured, and which OS you are building the app on. Here are some examples of binary paths using default build configurations for a hypothetical app called `myApp` which is built in the `workspace/myApp` directory: #### MacOS (Arm)[​](#macos-arm "Direct link to MacOS (Arm)") ``` '/workspace/myApp/dist-electron/mac-arm64/myApp.app/Contents/MacOS/myApp'; // Electron Builder '/workspace/myApp/out/myApp-darwin-arm64/myApp.app/Contents/MacOS/myApp'; // Electron Forge ``` #### MacOS (Intel)[​](#macos-intel "Direct link to MacOS (Intel)") ``` '/workspace/myApp/dist-electron/mac-x64/myApp.app/Contents/MacOS/myApp'; // Electron Builder '/workspace/myApp/out/myApp-darwin-x64/myApp.app/Contents/MacOS/myApp'; // Electron Forge ``` #### MacOS (Universal)[​](#macos-universal "Direct link to MacOS (Universal)") ``` '/workspace/myApp/dist-electron/mac-universal/myApp.app/Contents/MacOS/myApp'; // Electron Builder '/workspace/myApp/out/myApp-darwin-universal/myApp.app/Contents/MacOS/myApp'; // Electron Forge ``` #### Linux[​](#linux "Direct link to Linux") ``` '/workspace/myApp/dist-electron/linux-unpacked/myApp'; // Electron Builder '/workspace/myApp/out/myApp-linux-x64/myApp'; // Electron Forge ``` #### Windows[​](#windows "Direct link to Windows") ``` 'C:\\workspace\\myApp\\dist-electron\\win-unpacked\\myApp.exe'; // Electron Builder 'C:\\workspace\\myApp\\out\\myApp-win32-x64\\myApp.exe'; // Electron Forge ``` Note: * The above examples assume electron-builder's `"directories": { "output": "dist-electron" }` config (default is `"dist"`). Your actual binary path depends on your electron-builder configuration. * Electron Forge uses a standardised output directory which can be represented as `out/{appName}-{OS}-{arch}` ### `appEntryPoint`:[​](#appentrypoint "Direct link to appentrypoint") * Type `string` The path to the unpackaged entry point of the app for testing, e.g. your `main.js`. You will need Electron installed to use this feature. The `appEntryPoint` value overrides `appBinaryPath` if both are set. **Warning - Deeplink Testing:** `appEntryPoint` cannot be used for protocol handler testing on Windows or Linux. Protocol handlers on these platforms require an OS-registered executable binary to function correctly with the `browser.electron.triggerDeeplink()` method. You must use a packaged binary instead (either by setting `appBinaryPath` or letting the service auto-detect it). macOS works with both packaged binaries and script-based apps. See the [Deeplink Testing guide](/docs/desktop-testing/electron/deeplink-testing.md) for complete setup instructions. ### `electronBuilderConfig`:[​](#electronbuilderconfig "Direct link to electronbuilderconfig") * Type `string` Path to a custom electron-builder configuration file. This is useful when you have multiple configurations (e.g., `electron-builder-staging.config.js`) that extend a common base configuration, and you need to tell the service which one to use for binary path detection. When this option is provided, the service will load this specific configuration file and resolve any `extends` chain to determine the output settings. Example: `'config/electron-builder-staging.config.js'` ### `clearMocks`:[​](#clearmocks "Direct link to clearmocks") * Type `boolean` * Default `false` Calls .mockClear() on all mocked APIs before each test. This will clear mock history, but not reset its implementation. ### `resetMocks`:[​](#resetmocks "Direct link to resetmocks") * Type `boolean` * Default `false` Calls .mockReset() on all mocked APIs before each test. This will clear mock history and reset its implementation to an empty function (will return undefined). ### `restoreMocks`:[​](#restoremocks "Direct link to restoremocks") * Type `boolean` * Default `false` Calls .mockRestore() on all mocked APIs before each test. This will restore the original API function, the mock will be removed. ### `cdpBridgeTimeout`:[​](#cdpbridgetimeout "Direct link to cdpbridgetimeout") * Type `number` * Default `10000 (10 seconds)` Timeout in milliseconds for any request using CdpBridge to the node debugger. ### `cdpBridgeWaitInterval`:[​](#cdpbridgewaitinterval "Direct link to cdpbridgewaitinterval") * Type `number` * Default `100` Interval in milliseconds to wait between attempts to connect to the node debugger. ### `cdpBridgeRetryCount`:[​](#cdpbridgeretrycount "Direct link to cdpbridgeretrycount") * Type `number` * Default `3` Number of attempts to connect to the node debugger before giving up. ### `apparmorAutoInstall`:[​](#apparmorautoinstall "Direct link to apparmorautoinstall") * Type `boolean | 'sudo'` * Default `false` Control automatic installation of AppArmor profiles on Linux if needed. This helps resolve Electron startup issues on Ubuntu 24.04+ and other AppArmor-enabled Linux distributions where unprivileged user namespace restrictions prevent Electron from starting. * `false` (default): Never install; warn and continue without AppArmor profile * `true`: Install only if running as root (no sudo) * `'sudo'`: Install if root or via non-interactive sudo (`sudo -n`) if available **Note:** This feature requires appropriate system permissions. When enabled, the service will attempt to create and load a custom AppArmor profile for your Electron binary if the system has AppArmor restrictions that would prevent Electron from starting. ### `captureMainProcessLogs`:[​](#capturemainprocesslogs "Direct link to capturemainprocesslogs") * Type `boolean` * Default `false` Enable capture of Electron main process console logs. When enabled, console output from `console.log()`, `console.warn()`, `console.error()`, etc. in the main process will be forwarded to WDIO logs with the `[Electron:MainProcess]` prefix. Uses Chrome DevTools Protocol (CDP) `Runtime.consoleAPICalled` events to capture logs in real-time. Requires the `EnableNodeCliInspectArguments` Electron fuse to be enabled. Example: ``` export const config = { services: [ ['electron', { captureMainProcessLogs: true, mainProcessLogLevel: 'info' }] ] }; ``` ### `captureRendererLogs`:[​](#capturerendererlogs "Direct link to capturerendererlogs") * Type `boolean` * Default `false` Enable capture of Electron renderer process console logs. When enabled, console output from `console.log()`, `console.warn()`, `console.error()`, etc. in renderer processes (browser windows) will be forwarded to WDIO logs with the `[Electron:Renderer]` prefix. Uses Puppeteer CDP sessions to capture logs from all renderer targets. Unlike main process logs, renderer logs work independently and do NOT require the `EnableNodeCliInspectArguments` fuse or main process CDP bridge. Example: ``` export const config = { services: [ ['electron', { captureRendererLogs: true, rendererLogLevel: 'info' }] ] }; ``` ### `mainProcessLogLevel`:[​](#mainprocessloglevel "Direct link to mainprocessloglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` Minimum log level for main process logs. Only logs at or above this level will be captured and forwarded. Log level priority (from lowest to highest): `trace` < `debug` < `info` < `warn` < `error` Example: ``` export const config = { services: [ ['electron', { captureMainProcessLogs: true, mainProcessLogLevel: 'warn' // Only capture warn and error logs }] ] }; ``` ### `rendererLogLevel`:[​](#rendererloglevel "Direct link to rendererloglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` Minimum log level for renderer process logs. Only logs at or above this level will be captured and forwarded. Log level priority (from lowest to highest): `trace` < `debug` < `info` < `warn` < `error` Example: ``` export const config = { services: [ ['electron', { captureRendererLogs: true, rendererLogLevel: 'debug' // Capture debug, info, warn, and error logs }] ] }; ``` ### `logDir`:[​](#logdir "Direct link to logdir") * Type `string` * Default `undefined (no file logging)` Directory path for log file output in standalone mode. When using `startWdioSession()` without the WDIO test runner, logs will be written to timestamped files in this directory instead of being forwarded to the WDIO logger. In test runner mode (normal WDIO usage), this option is ignored and logs are forwarded to the WDIO logger under your configured `outputDir`. Example: ``` import { startWdioSession } from '@wdio/electron-service'; const browser = await startWdioSession([{ browserName: 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/binary', captureMainProcessLogs: true, captureRendererLogs: true, logDir: './logs' // Logs written to ./logs/wdio-{timestamp}.log } }]); ``` ## Log Output Format[​](#log-output-format "Direct link to Log Output Format") ### Test Runner Mode[​](#test-runner-mode "Direct link to Test Runner Mode") Logs are forwarded to WDIO's logger and appear in your test output with appropriate prefixes: ``` [Electron:MainProcess] Application started [Electron:Renderer] Page loaded successfully [Electron:MainProcess:app1] Multiremote instance log ``` ### Standalone Mode[​](#standalone-mode "Direct link to Standalone Mode") Logs are written to timestamped files with full metadata: ``` 2025-12-29T19:07:00.123Z INFO electron-service:service: [Electron:MainProcess] Application started 2025-12-29T19:07:01.456Z WARN electron-service:service: [Electron:Renderer] Deprecated API used ``` ## Multiremote Support[​](#multiremote-support "Direct link to Multiremote Support") When using multiremote configurations, logs automatically include the instance ID: ``` export const config = { capabilities: { app1: { capabilities: { browserName: 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/app1', captureMainProcessLogs: true } } }, app2: { capabilities: { browserName: 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/app2', captureMainProcessLogs: true } } } } }; ``` Output: ``` [Electron:MainProcess:app1] App 1 started [Electron:MainProcess:app2] App 2 started ``` ## Log Capture Requirements[​](#log-capture-requirements "Direct link to Log Capture Requirements") **Main Process Logs:** * Requires the `EnableNodeCliInspectArguments` Electron fuse to be enabled * Requires CDP bridge connection to main process * If CDP bridge is unavailable (e.g., fuse disabled), main process log capture will be disabled with a warning **Renderer Process Logs:** * Uses Puppeteer CDP sessions - works independently of main process CDP bridge * Does NOT require the `EnableNodeCliInspectArguments` fuse * Will continue to work even if main process CDP bridge is unavailable This means you can capture renderer logs even when the CDP bridge is unavailable for the main process. ## Automatic detection of App binary[​](#automatic-detection-of-app-binary "Direct link to Automatic detection of App binary") The service will automatically determine the path to the Electron binary of your app based on the configuration of supported build tools. If you want to manually set this value, you can specify the [`appBinaryPath`](#appbinarypath) option. ### Build tool compatibility[​](#build-tool-compatibility "Direct link to Build tool compatibility") The v10 release is exercised in CI against: * **electron-builder** 26.x * **@electron-forge/cli** 7.x Other 2.x and 7.x versions generally work because the layout of `dist-electron/` and `out/` paths has been stable across these majors. If you run into a detection issue with a specific version, please open an issue with your build tool config so the path resolver can be updated. ### Supported config locations:[​](#supported-config-locations "Direct link to Supported config locations:") ##### Electron Builder[​](#electron-builder "Direct link to Electron Builder") * `package.json` (config values are read from `build`) * `electron-builder.{json,json5,yaml,yml,toml,js,ts,mjs,cjs,mts,cts}` * `electron-builder.config.{json,json5,yaml,yml,toml,js,ts,mjs,cjs,mts,cts}` * Custom config file specified via [`electronBuilderConfig`](#electronbuilderconfig) **Note:** The service supports the [`extends`](https://www.electron.build/configuration/configuration#extends) option in electron-builder configurations. It will recursively resolve and merge extended configurations to determine the final build settings. ##### Electron Forge[​](#electron-forge "Direct link to Electron Forge") * `package.json` (config values are read from `config.forge`) * `forge.config.js` * `custom.config.js` (e.g. when `"config": { "forge": "./custom-config.js" }` is specified in package.json) ## Chromedriver Configuration[​](#chromedriver-configuration "Direct link to Chromedriver Configuration") `wdio-electron-service` needs Chromedriver to work. The Chromedriver version needs to be appropriate for the version of Electron that your app was built with, you can either let the service handle this (default) or manage it yourself. ### Service Managed[​](#service-managed "Direct link to Service Managed") If you are not specifying a Chromedriver binary then the service will download and use the appropriate version for your app's Electron version. The Electron version of your app is determined by the version of `electron` or `electron-nightly` in your `package.json`, however you may want to override this behaviour - for instance, if the app you are testing is in a different repo from the tests. You can specify the Electron version manually by setting the `browserVersion` capability, as shown in the example configuration below: *`wdio.conf.ts`* ``` export const config = { // ... services: ['electron'], capabilities: [ { browserName: 'electron', browserVersion: '28.0.0', }, ], // ... }; ``` ### User Managed[​](#user-managed "Direct link to User Managed") In order to manage Chromedriver yourself you can install it directly or via some other means like [`electron-chromedriver`](https://github.com/electron/chromedriver), in this case you will need to tell WebdriverIO where your Chromedriver binary is through its custom [`wdio:chromedriverOptions`](https://webdriver.io/docs/capabilities#webdriverio-capabilities-to-manage-browser-driver-options) capability. For example, in order to use WDIO with an Electron v19 app, you will have to download Chromedriver `102.0.5005.61` from . You should then specify the binary path in the WDIO config as follows: *`wdio.conf.ts`* ``` export const config = { // ... services: ['electron'], capabilities: [ { 'browserName': 'electron', 'wdio:chromedriverOptions': { binary: '/Users/wdio/Downloads/chromedriver', // path to Chromedriver you just downloaded }, }, ], // ... }; ``` --- Source: https://webdriver.io/docs/desktop-testing/electron/api.md # Accessing Electron APIs This guide covers how to work with Electron APIs in your tests, including accessing APIs from the main process and mocking them for testing. ## Accessing Electron APIs[​](#accessing-electron-apis "Direct link to Accessing Electron APIs") The service provides access to Electron APIs from the main process using the Chrome DevTools Protocol (CDP). You can access these APIs by using the `browser.electron.execute()` method in your test suites. ### Execute Scripts[​](#execute-scripts "Direct link to Execute Scripts") Arbitrary scripts can be executed within the context of your Electron application main process using `browser.electron.execute()`. This allows Electron APIs to be accessed in a fluid way, in case you wish to manipulate your application at runtime or trigger certain events. For example, a message modal can be triggered from a test via: ``` await browser.electron.execute( (electron, param1, param2, param3) => { const appWindow = electron.BrowserWindow.getFocusedWindow(); electron.dialog.showMessageBox(appWindow, { message: 'Hello World!', detail: `${param1} + ${param2} + ${param3} = ${param1 + param2 + param3}`, }); }, 1, 2, 3, ); ``` ...which results in the application displaying the following alert: ![Execute Demo](https://raw.githubusercontent.com/webdriverio/desktop-mobile/37081c940a4528df3bf1994d9a5391d33a8775d5/packages/electron-service/.github/assets/execute-demo.png "Execute Demo") **Note:** The first argument of the function is always the default export of the `electron` package that contains the [Electron API](https://www.electronjs.org/docs/latest/api/app). ### How It Works[​](#how-it-works "Direct link to How It Works") The service uses the Chrome DevTools Protocol (CDP) to communicate with your Electron application's main process. This provides a reliable and efficient way to: * Execute JavaScript code in the main process context * Access all Electron APIs * Mock Electron APIs for testing * Handle multiple windows and processes No additional setup or imports are required in your Electron application - the service automatically connects to your app when it starts. ## Mocking Electron APIs[​](#mocking-electron-apis "Direct link to Mocking Electron APIs") The service allows for mocking of Electron API functionality via a [Vitest](https://vitest.dev/)-like interface. ### Creating Mocks[​](#creating-mocks "Direct link to Creating Mocks") Use `browser.electron.mock()` to mock individual Electron API functions: ``` const mockedShowOpenDialog = await browser.electron.mock('dialog', 'showOpenDialog'); await browser.electron.execute( async (electron) => await electron.dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'], }), ); expect(mockedShowOpenDialog).toHaveBeenCalledTimes(1); expect(mockedShowOpenDialog).toHaveBeenCalledWith({ properties: ['openFile', 'openDirectory'], }); ``` Use `browser.electron.mockAll()` to mock all functions on an API simultaneously: ``` const { showOpenDialog, showMessageBox } = await browser.electron.mockAll('dialog'); await showOpenDialog.mockReturnValue('I opened a dialog!'); await showMessageBox.mockReturnValue('I opened a message box!'); ``` ### Mocking Electron Classes[​](#mocking-electron-classes "Direct link to Mocking Electron Classes") For Electron classes like `Tray`, `BrowserWindow`, `Menu`, etc., you can mock the entire class and all its instance methods: ``` // Mock the Tray class const mockTray = await browser.electron.mock('Tray'); // Mock instance methods await mockTray.setTitle.mockReturnValue(undefined); await mockTray.setToolTip.mockReturnValue(undefined); // Track constructor calls const tray = await browser.electron.execute((electron) => new electron.Tray('/path/to/icon.png')); expect(mockTray.__constructor).toHaveBeenCalledWith('/path/to/icon.png'); // Test instance method calls await browser.electron.execute((electron) => { const tray = new electron.Tray('/path/to/icon.png'); tray.setTitle('My App'); tray.setToolTip('Click for menu'); }); expect(mockTray.setTitle).toHaveBeenCalledWith('My App'); expect(mockTray.setToolTip).toHaveBeenCalledWith('Click for menu'); ``` Class mocks provide: * **`__constructor`**: An ElectronFunctionMock object that tracks calls to the class constructor * **Instance methods**: All class instance methods are available as mock objects * **`mockRestore()`**: Method to restore the original class ### Setting Return Values[​](#setting-return-values "Direct link to Setting Return Values") Mock objects provide methods to control what the mocked function returns: ``` const mockGetName = await browser.electron.mock('app', 'getName'); // Return a specific value await mockGetName.mockReturnValue('mocked app name'); // Return different values for consecutive calls await mockGetName.mockReturnValueOnce('first call'); await mockGetName.mockReturnValueOnce('second call'); // For async functions, use mockResolvedValue const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); await mockGetFileIcon.mockResolvedValue('mocked icon data'); ``` ### Custom Implementations[​](#custom-implementations "Direct link to Custom Implementations") You can provide custom implementations for mocks: ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockImplementation((customName) => { return customName || 'default name'; }); const result = await browser.electron.execute( (electron) => electron.app.getName('custom') ); expect(result).toBe('custom'); ``` ### Managing Mocks[​](#managing-mocks "Direct link to Managing Mocks") The service provides utilities to manage multiple mocks: ``` // Clear mock call history (keeps implementation) await browser.electron.clearAllMocks(); await browser.electron.clearAllMocks('app'); // Clear only app mocks // Reset mocks (clears history and implementation) await browser.electron.resetAllMocks(); await browser.electron.resetAllMocks('clipboard'); // Reset only clipboard mocks // Restore original implementations await browser.electron.restoreAllMocks(); await browser.electron.restoreAllMocks('dialog'); // Restore only dialog mocks ``` You can also manage individual mocks: ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockClear(); // Clear call history await mockGetName.mockReset(); // Clear history and implementation await mockGetName.mockRestore(); // Restore original function ``` ### Inspecting Mock Calls[​](#inspecting-mock-calls "Direct link to Inspecting Mock Calls") Mock objects track how they were called: ``` const mockSetName = await browser.electron.mock('app', 'setName'); await browser.electron.execute((electron) => electron.app.setName('test')); await browser.electron.execute((electron) => electron.app.setName('test 2')); // Check all calls expect(mockSetName.mock.calls).toStrictEqual([ ['test'], ['test 2'], ]); // Check last call expect(mockSetName.mock.lastCall).toStrictEqual(['test 2']); // Check results expect(mockSetName.mock.results).toHaveLength(2); ``` ### Service Configuration[​](#service-configuration "Direct link to Service Configuration") You can automatically manage mocks before each test using service configuration: ``` export const config = { services: [ ['electron', { clearMocks: true, // Calls mockClear() before each test resetMocks: false, // Calls mockReset() before each test restoreMocks: false // Calls mockRestore() before each test }] ] }; ``` ## API Reference[​](#api-reference "Direct link to API Reference") For complete API documentation including all parameters, return types, and mock object methods: * [API Reference - `execute()`](/docs/desktop-testing/electron/api-reference.md#execute) * [API Reference - Mocking Methods](/docs/desktop-testing/electron/api-reference.md#mocking-methods) * [API Reference - Mock Object Methods](/docs/desktop-testing/electron/api-reference.md#mock-object-methods) * [API Reference - Mock Object Properties](/docs/desktop-testing/electron/api-reference.md#mock-object-properties) * [API Reference - Electron Class Mock](/docs/desktop-testing/electron/api-reference.md#electron-class-mock) --- Source: https://webdriver.io/docs/desktop-testing/electron/api-reference.md # API Reference This document provides a complete reference for all `browser.electron.*` methods and exported utility functions provided by the service. ## Table of Contents[​](#table-of-contents "Direct link to Table of Contents") * [Utility Functions](#utility-functions) * [`createElectronCapabilities()`](#createelectroncapabilities) * [`getElectronBinaryPath()`](#getelectronbinarypath) * [`startWdioSession()`](#startwdiosession) * [`cleanupWdioSession()`](#cleanupwdiosession) * [Execution Methods](#execution-methods) * [`execute()`](#execute) * [`triggerDeeplink()`](#triggerdeeplink) * [Mocking Methods](#mocking-methods) * [`mock()`](#mock) * [`mockAll()`](#mockall) * [`clearAllMocks()`](#clearallmocks) * [`resetAllMocks()`](#resetallmocks) * [`restoreAllMocks()`](#restoreallmocks) * [`isMockFunction()`](#ismockfunction) * [Mock Object Methods](#mock-object-methods) * [`mockImplementation()`](#mockimplementation) * [`mockImplementationOnce()`](#mockimplementationonce) * [`mockReturnValue()`](#mockreturnvalue) * [`mockReturnValueOnce()`](#mockreturnvalueonce) * [`mockResolvedValue()`](#mockresolvedvalue) * [`mockResolvedValueOnce()`](#mockresolvedvalueonce) * [`mockRejectedValue()`](#mockrejectedvalue) * [`mockRejectedValueOnce()`](#mockrejectedvalueonce) * [`mockClear()`](#mockclear) * [`mockReset()`](#mockreset) * [`mockRestore()`](#mockrestore) * [`withImplementation()`](#withimplementation) * [`getMockImplementation()`](#getmockimplementation) * [`getMockName()`](#getmockname) * [`mockName()`](#mockname) * [`mockReturnThis()`](#mockreturnthis) * [Mock Object Properties](#mock-object-properties) * [`mock.calls`](#mockcalls) * [`mock.lastCall`](#mocklastcall) * [`mock.results`](#mockresults) * [`mock.invocationCallOrder`](#mockinvocationcallorder) * [Electron Class Mock](#electron-class-mock) * [`__constructor`](#__constructor) * [`[methodName]`](#methodname) * [`getMockName()`](#getmockname) * [`mockRestore()`](#mockrestore) ## Utility Functions[​](#utility-functions "Direct link to Utility Functions") These functions are exported directly from the package and can be used independently of the WDIO test runner. ### `createElectronCapabilities()`[​](#createelectroncapabilities "Direct link to createelectroncapabilities") Creates an Electron capabilities object for use with `startWdioSession()` or in WDIO configuration. Builds the correct capability structure including `goog:chromeOptions` and `wdio:electronServiceOptions`. **Signature:** ``` import { createElectronCapabilities } from '@wdio/electron-service'; createElectronCapabilities(options: ElectronServiceOptions): ElectronStandaloneCapability ``` **Parameters:** | Parameter | Type | Description | | --------- | ------------------------ | -------------------------------------------------------------------------- | | `options` | `ElectronServiceOptions` | Service options. Must include at least `appBinaryPath` or `appEntryPoint`. | Common fields: | Field | Type | Description | | ------------------------ | ---------- | -------------------------------------------------------- | | `appBinaryPath` | `string` | Path to the compiled Electron app binary | | `appEntryPoint` | `string` | Path to the unpackaged app entry point (e.g., `main.js`) | | `appArgs` | `string[]` | Command-line arguments passed to the app | | `captureMainProcessLogs` | `boolean` | Enable main process log capture | | `captureRendererLogs` | `boolean` | Enable renderer process log capture | | `logDir` | `string` | Directory for standalone mode logs | See [Configuration](/docs/desktop-testing/electron/configuration.md) for the full list of `ElectronServiceOptions` fields. **Returns:** `ElectronStandaloneCapability` - A single capabilities object **Throws:** | Error | Condition | | ------- | ---------------------------------------------------------- | | `Error` | If neither `appBinaryPath` nor `appEntryPoint` is provided | **Example:** ``` import { startWdioSession, createElectronCapabilities } from '@wdio/electron-service'; const caps = createElectronCapabilities({ appBinaryPath: './dist/mac/MyApp.app/Contents/MacOS/MyApp', appArgs: ['--disable-gpu', '--headless'], captureMainProcessLogs: true, logDir: './test-logs', }); const browser = await startWdioSession([caps]); ``` **See Also:** * [Standalone Mode](/docs/desktop-testing/electron/standalone.md) * [Configuration](/docs/desktop-testing/electron/configuration.md) ### `getElectronBinaryPath()`[​](#getelectronbinarypath "Direct link to getelectronbinarypath") Resolves the path to the Electron binary for a given app directory. Uses the same detection logic as the service (reading `package.json`, checking Electron Forge/Builder configs) without starting a session. **Signature:** ``` import { getElectronBinaryPath } from '@wdio/electron-service'; getElectronBinaryPath(appDir: string): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------ | | `appDir` | `string` | Path to the Electron app directory (must contain a `package.json`) | **Returns:** `Promise` - The resolved path to the Electron binary **Throws:** | Error | Condition | | ------- | ----------------------------------------- | | `Error` | If no `package.json` is found in `appDir` | | `Error` | If the binary path cannot be resolved | **Example:** ``` import { getElectronBinaryPath } from '@wdio/electron-service'; const binaryPath = await getElectronBinaryPath('/path/to/my-electron-app'); console.log(binaryPath); // e.g. '/path/to/my-electron-app/dist/mac-arm64/MyApp.app/Contents/MacOS/MyApp' ``` **See Also:** * [Configuration - Automatic detection of App binary](/docs/desktop-testing/electron/configuration.md#automatic-detection-of-app-binary) ### `startWdioSession()`[​](#startwdiosession "Direct link to startwdiosession") Starts a WebdriverIO session in standalone mode (without the WDIO test runner). Performs the same launcher setup the runner does — binary detection, capability mutation, log writer initialization — and returns a browser instance. **Signature:** ``` import { startWdioSession } from '@wdio/electron-service'; startWdioSession( capabilities: ElectronServiceCapabilities, globalOptions?: ElectronServiceGlobalOptions, ): Promise ``` **Parameters:** | Parameter | Type | Description | | --------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `capabilities` | `ElectronServiceCapabilities` | An array of standalone capability objects (typically one, built with [`createElectronCapabilities()`](#createelectroncapabilities)), or a multiremote capabilities object. | | `globalOptions` | `ElectronServiceGlobalOptions` | Optional. Service-level options applied to all capabilities (e.g., `rootDir`). | **Returns:** `Promise` - The browser instance, with `browser.electron.*` available. **Example:** ``` import { startWdioSession, cleanupWdioSession, createElectronCapabilities } from '@wdio/electron-service'; const caps = createElectronCapabilities({ appBinaryPath: '/path/to/MyApp', captureMainProcessLogs: true, logDir: './logs', }); const browser = await startWdioSession([caps]); try { const name = await browser.electron.execute((electron) => electron.app.getName()); console.log(name); } finally { await cleanupWdioSession(browser); } ``` **See Also:** * [Standalone Mode](/docs/desktop-testing/electron/standalone.md) * [`cleanupWdioSession()`](#cleanupwdiosession) ### `cleanupWdioSession()`[​](#cleanupwdiosession "Direct link to cleanupwdiosession") Tears down a standalone session started with [`startWdioSession()`](#startwdiosession). Calls `browser.deleteSession()` and runs the launcher's `onComplete` cleanup so the Electron process and any spawned drivers are released. **Signature:** ``` import { cleanupWdioSession } from '@wdio/electron-service'; cleanupWdioSession(browser: WebdriverIO.Browser): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | --------------------- | -------------------------------------------------------- | | `browser` | `WebdriverIO.Browser` | The browser instance returned from `startWdioSession()`. | **Returns:** `Promise` **See Also:** * [Standalone Mode](/docs/desktop-testing/electron/standalone.md) * [`startWdioSession()`](#startwdiosession) ## Execution Methods[​](#execution-methods "Direct link to Execution Methods") ### `execute()`[​](#execute "Direct link to execute") Executes arbitrary JavaScript code in the Electron main process context. **Signature:** ``` browser.electron.execute( script: (electron, ...args) => T | Promise, ...args: any[] ): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ---------------------------------------- | ------------------------------------------------------------------------------- | | `script` | `(electron, ...args) => T \| Promise` | Function to execute in main process. First arg is always the `electron` module. | | `...args` | `any[]` | Additional arguments passed to the script function | **Returns:** `Promise` - Resolves with the return value of the script **Example:** ``` // Simple execution const appName = await browser.electron.execute((electron) => { return electron.app.getName(); }); // With parameters const result = await browser.electron.execute( (electron, param1, param2) => { return param1 + param2; }, 5, 10 ); // With async code const fileIcon = await browser.electron.execute(async (electron) => { return await electron.app.getFileIcon('/path/to/file'); }); ``` **See Also:** * [Electron APIs Guide](/docs/desktop-testing/electron/api.md) ### `triggerDeeplink()`[​](#triggerdeeplink "Direct link to triggerdeeplink") Triggers a deeplink to the Electron application for testing protocol handlers. On Windows and Linux, this automatically appends the test instance's `userData` directory to ensure the deeplink reaches the correct instance. On macOS, it works transparently without modification. **Signature:** ``` browser.electron.triggerDeeplink(url: string): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | The deeplink URL to trigger (e.g., `'myapp://open?path=/test'`). Must use a custom protocol scheme (not http/https/file). | **Returns:** `Promise` - Resolves when the deeplink has been triggered. **Throws:** | Error | Condition | | ------- | --------------------------------------------------------- | | `Error` | If `appBinaryPath` is not configured (Windows/Linux only) | | `Error` | If the URL is invalid or malformed | | `Error` | If the URL uses http/https/file protocols | | `Error` | If the platform is unsupported | | `Error` | If the command to trigger the deeplink fails | **Example:** ``` // Basic usage await browser.electron.triggerDeeplink('myapp://open?file=test.txt'); // With complex parameters await browser.electron.triggerDeeplink('myapp://action?id=123&type=user&tags[]=a&tags[]=b'); // In a test with verification it('should handle deeplinks', async () => { await browser.electron.triggerDeeplink('myapp://navigate?to=/settings'); await browser.waitUntil(async () => { const currentPath = await browser.electron.execute(() => { return globalThis.currentPath; }); return currentPath === '/settings'; }, { timeout: 5000, timeoutMsg: 'App did not process the deeplink' }); }); ``` **Platform-Specific Behavior:** * **Windows**: Cannot use `appEntryPoint` (must use packaged binary). Automatically appends `userData` parameter to URL. * **macOS**: Works with both packaged binaries and script-based apps. No URL modification. * **Linux**: Cannot use `appEntryPoint` (must use packaged binary). Automatically appends `userData` parameter to URL. **See Also:** * [Deeplink Testing Guide](/docs/desktop-testing/electron/deeplink-testing.md) ## Mocking Methods[​](#mocking-methods "Direct link to Mocking Methods") ### `mock()`[​](#mock "Direct link to mock") Mocks an Electron API function when provided with an API name and function name. Returns a [mock object](#mock-object-methods). When called with only an API name (no function name), mocks an entire Electron class (e.g., `'Tray'`, `'BrowserWindow'`). Returns an [Electron class mock object](#electron-class-mock). **Signature:** ``` // Mock a specific function browser.electron.mock(apiName: string, funcName: string): Promise // Mock an entire class browser.electron.mock(className: string): Promise ``` **Parameters:** | Parameter | Type | Description | | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------- | | `apiName` | `string` | The Electron API module name (e.g., `'dialog'`, `'app'`, `'clipboard'`) or class name (e.g., `'Tray'`, `'BrowserWindow'`) | | `funcName` | `string` | **Optional.** The function name to mock (e.g., `'showOpenDialog'`, `'getName'`). If omitted, mocks the entire class. | **Returns:** `Promise` - An Electron mock object (function mock or class mock) with methods for controlling and inspecting the mock **Example:** ``` const mockedShowOpenDialog = await browser.electron.mock('dialog', 'showOpenDialog'); await browser.electron.execute( async (electron) => await electron.dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'], }), ); expect(mockedShowOpenDialog).toHaveBeenCalledTimes(1); expect(mockedShowOpenDialog).toHaveBeenCalledWith({ properties: ['openFile', 'openDirectory'], }); // Class mocking const mockTray = await browser.electron.mock('Tray'); await mockTray.setTitle.mockReturnValue(undefined); // Track constructor calls const tray = await browser.electron.execute((electron) => new electron.Tray('/path/to/icon.png')); expect(mockTray.__constructor).toHaveBeenCalledWith('/path/to/icon.png'); // Mock instance methods await browser.electron.execute((electron) => { const tray = new electron.Tray('/path/to/icon.png'); tray.setTitle('My App'); }); expect(mockTray.setTitle).toHaveBeenCalledWith('My App'); ``` **See Also:** * [Electron APIs Guide](/docs/desktop-testing/electron/api.md#mocking-electron-apis) ### `mockAll()`[​](#mockall "Direct link to mockall") Mocks all functions on an Electron API module simultaneously. Returns an object containing all mocks. **Signature:** ``` browser.electron.mockAll(apiName: string): Promise> ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | -------------------------------------------------------- | | `apiName` | `string` | The Electron API module name (e.g., `'dialog'`, `'app'`) | **Returns:** `Promise>` - Object with function names as keys and mock objects as values **Example:** ``` const { showOpenDialog, showMessageBox } = await browser.electron.mockAll('dialog'); await showOpenDialog.mockReturnValue('I opened a dialog!'); await showMessageBox.mockReturnValue('I opened a message box!'); ``` **See Also:** * [Electron APIs Guide](/docs/desktop-testing/electron/api.md#mocking-electron-apis) ### `clearAllMocks()`[​](#clearallmocks "Direct link to clearallmocks") Calls [`mockClear()`](#mockclear) on all active mocks, or on mocks of a specific API if `apiName` is provided. **Signature:** ``` browser.electron.clearAllMocks(apiName?: string): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------- | | `apiName` | `string` | Optional. If provided, only clears mocks of this specific API | **Returns:** `Promise` **Example:** ``` // Clear all mocks const mockSetName = await browser.electron.mock('app', 'setName'); const mockWriteText = await browser.electron.mock('clipboard', 'writeText'); await browser.electron.execute((electron) => electron.app.setName('new app name')); await browser.electron.execute((electron) => electron.clipboard.writeText('text to be written')); await browser.electron.clearAllMocks(); expect(mockSetName.mock.calls).toStrictEqual([]); expect(mockWriteText.mock.calls).toStrictEqual([]); // Clear mocks of specific API await browser.electron.clearAllMocks('app'); expect(mockSetName.mock.calls).toStrictEqual([]); expect(mockWriteText.mock.calls).toStrictEqual([['text to be written']]); ``` ### `resetAllMocks()`[​](#resetallmocks "Direct link to resetallmocks") Calls [`mockReset()`](#mockreset) on all active mocks, or on mocks of a specific API if `apiName` is provided. **Signature:** ``` browser.electron.resetAllMocks(apiName?: string): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------- | | `apiName` | `string` | Optional. If provided, only resets mocks of this specific API | **Returns:** `Promise` **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); const mockReadText = await browser.electron.mock('clipboard', 'readText'); await mockGetName.mockReturnValue('mocked appName'); await mockReadText.mockReturnValue('mocked clipboardText'); await browser.electron.resetAllMocks(); const appName = await browser.electron.execute((electron) => electron.app.getName()); const clipboardText = await browser.electron.execute((electron) => electron.clipboard.readText()); expect(appName).toBeUndefined(); expect(clipboardText).toBeUndefined(); ``` ### `restoreAllMocks()`[​](#restoreallmocks "Direct link to restoreallmocks") Calls [`mockRestore()`](#mockrestore) on all active mocks, or on mocks of a specific API if `apiName` is provided. **Signature:** ``` browser.electron.restoreAllMocks(apiName?: string): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | --------------------------------------------------------------- | | `apiName` | `string` | Optional. If provided, only restores mocks of this specific API | **Returns:** `Promise` **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); const mockReadText = await browser.electron.mock('clipboard', 'readText'); await mockGetName.mockReturnValue('mocked appName'); await mockReadText.mockReturnValue('mocked clipboardText'); await browser.electron.restoreAllMocks(); const appName = await browser.electron.execute((electron) => electron.app.getName()); const clipboardText = await browser.electron.execute((electron) => electron.clipboard.readText()); expect(appName).toBe('my real app name'); expect(clipboardText).toBe('some real clipboard text'); ``` ### `isMockFunction()`[​](#ismockfunction "Direct link to ismockfunction") Checks if a given parameter is an Electron mock function. If using TypeScript, narrows down the type. **Signature:** ``` browser.electron.isMockFunction(fn: any): fn is ElectronMock ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | ------------------ | | `fn` | `any` | The value to check | **Returns:** `boolean` - `true` if the value is a mock function, `false` otherwise **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); expect(browser.electron.isMockFunction(mockGetName)).toBe(true); expect(browser.electron.isMockFunction(() => {})).toBe(false); ``` ## Mock Object Methods[​](#mock-object-methods "Direct link to Mock Object Methods") Each mock object returned by [`mock()`](#mock) or [`mockAll()`](#mockall) has the following methods: ### `mockImplementation()`[​](#mockimplementation "Direct link to mockimplementation") Accepts a function that will be used as the implementation of the mock. **Signature:** ``` mockImplementation(fn: (...args: any[]) => any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ------------------------- | -------------------------------------- | | `fn` | `(...args: any[]) => any` | Function to use as mock implementation | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); let callsCount = 0; await mockGetName.mockImplementation(() => { if (typeof callsCount !== 'undefined') { callsCount++; } return 'mocked value'; }); const result = await browser.electron.execute(async (electron) => await electron.app.getName()); expect(callsCount).toBe(1); expect(result).toBe('mocked value'); ``` ### `mockImplementationOnce()`[​](#mockimplementationonce "Direct link to mockimplementationonce") Accepts a function that will be used as mock's implementation during the next call. If chained, every consecutive call will produce different results. When the queued implementations run out, the mock falls back to whatever was set via [`mockImplementation()`](#mockimplementation); if no default has been set, calls return `undefined` (or `null` when the original API returns `null`). **Signature:** ``` mockImplementationOnce(fn: (...args: any[]) => any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ------------------------- | --------------------------------- | | `fn` | `(...args: any[]) => any` | Function to use for the next call | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockImplementationOnce(() => 'first mock'); await mockGetName.mockImplementationOnce(() => 'second mock'); let name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBe('first mock'); name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBe('second mock'); name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBeNull(); ``` ### `mockReturnValue()`[​](#mockreturnvalue "Direct link to mockreturnvalue") Accepts a value that will be returned whenever the mock function is called. **Signature:** ``` mockReturnValue(value: any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | ----------------------------- | | `value` | `any` | Value to return from the mock | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockReturnValue('mocked name'); const name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBe('mocked name'); ``` ### `mockReturnValueOnce()`[​](#mockreturnvalueonce "Direct link to mockreturnvalueonce") Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value. When values run out, falls back to the previously defined implementation. **Signature:** ``` mockReturnValueOnce(value: any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | --------------------------------- | | `value` | `any` | Value to return for the next call | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockReturnValueOnce('first mock'); await mockGetName.mockReturnValueOnce('second mock'); let name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBe('first mock'); name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBe('second mock'); name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBeNull(); ``` ### `mockResolvedValue()`[​](#mockresolvedvalue "Direct link to mockresolvedvalue") Accepts a value that will be resolved (for async functions) whenever the mock is called. **Signature:** ``` mockResolvedValue(value: any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | ------------------------------ | | `value` | `any` | Value to resolve from the mock | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); await mockGetFileIcon.mockResolvedValue('This is a mock'); const fileIcon = await browser.electron.execute(async (electron) => await electron.app.getFileIcon('/path/to/icon')); expect(fileIcon).toBe('This is a mock'); ``` ### `mockResolvedValueOnce()`[​](#mockresolvedvalueonce "Direct link to mockresolvedvalueonce") Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve the specified value. When values run out, falls back to the previously defined implementation. **Signature:** ``` mockResolvedValueOnce(value: any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | ---------------------------------- | | `value` | `any` | Value to resolve for the next call | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); await mockGetFileIcon.mockResolvedValue('default mocked icon'); await mockGetFileIcon.mockResolvedValueOnce('first mocked icon'); await mockGetFileIcon.mockResolvedValueOnce('second mocked icon'); let fileIcon = await browser.electron.execute(async (electron) => await electron.app.getFileIcon('/path/to/icon')); expect(fileIcon).toBe('first mocked icon'); fileIcon = await browser.electron.execute(async (electron) => await electron.app.getFileIcon('/path/to/icon')); expect(fileIcon).toBe('second mocked icon'); fileIcon = await browser.electron.execute(async (electron) => await electron.app.getFileIcon('/path/to/icon')); expect(fileIcon).toBe('default mocked icon'); ``` ### `mockRejectedValue()`[​](#mockrejectedvalue "Direct link to mockrejectedvalue") Accepts a value that will be rejected (for async functions) whenever the mock is called. **Signature:** ``` mockRejectedValue(value: any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | ----------------------------- | | `value` | `any` | Value to reject from the mock | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); await mockGetFileIcon.mockRejectedValue('This is a mock error'); const fileIconError = await browser.electron.execute(async (electron) => { try { await electron.app.getFileIcon('/path/to/icon'); } catch (e) { return e; } }); expect(fileIconError).toBe('This is a mock error'); ``` ### `mockRejectedValueOnce()`[​](#mockrejectedvalueonce "Direct link to mockrejectedvalueonce") Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject the specified value. When values run out, falls back to the previously defined implementation. **Signature:** ``` mockRejectedValueOnce(value: any): Promise ``` **Parameters:** | Parameter | Type | Description | | --------- | ----- | --------------------------------- | | `value` | `any` | Value to reject for the next call | **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); await mockGetFileIcon.mockRejectedValue('default mocked icon error'); await mockGetFileIcon.mockRejectedValueOnce('first mocked icon error'); await mockGetFileIcon.mockRejectedValueOnce('second mocked icon error'); const getFileIcon = async () => await browser.electron.execute(async (electron) => { try { await electron.app.getFileIcon('/path/to/icon'); } catch (e) { return e; } }); let fileIcon = await getFileIcon(); expect(fileIcon).toBe('first mocked icon error'); fileIcon = await getFileIcon(); expect(fileIcon).toBe('second mocked icon error'); fileIcon = await getFileIcon(); expect(fileIcon).toBe('default mocked icon error'); ``` ### `mockClear()`[​](#mockclear "Direct link to mockclear") Clears the history of the mocked function. The mock implementation will not be reset. **Signature:** ``` mockClear(): Promise ``` **Returns:** `Promise` **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await browser.electron.execute((electron) => electron.app.getName()); await mockGetName.mockClear(); await browser.electron.execute((electron) => electron.app.getName()); expect(mockGetName).toHaveBeenCalledTimes(1); ``` ### `mockReset()`[​](#mockreset "Direct link to mockreset") Resets the mocked function. The mock history will be cleared and the implementation will be reset to an empty function (returning undefined). Also resets all "once" implementations. **Signature:** ``` mockReset(): Promise ``` **Returns:** `Promise` **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockReturnValue('mocked name'); await browser.electron.execute((electron) => electron.app.getName()); await mockGetName.mockReset(); const name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBeUndefined(); expect(mockGetName).toHaveBeenCalledTimes(1); ``` ### `mockRestore()`[​](#mockrestore "Direct link to mockrestore") Restores the original implementation to the Electron API function. **Signature:** ``` mockRestore(): Promise ``` **Returns:** `Promise` **Example:** ``` const appName = await browser.electron.execute((electron) => electron.app.getName()); const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockReturnValue('mocked name'); await mockGetName.mockRestore(); const name = await browser.electron.execute((electron) => electron.app.getName()); expect(name).toBe(appName); ``` ### `withImplementation()`[​](#withimplementation "Direct link to withimplementation") Overrides the original mock implementation temporarily while the callback is being executed. The electron object is passed into the callback in the same way as for [`execute()`](#execute). **Signature:** ``` withImplementation( implementation: (...args: any[]) => any, callback: (electron) => any ): Promise ``` **Parameters:** | Parameter | Type | Description | | ---------------- | ------------------------- | ---------------------------------------------------------- | | `implementation` | `(...args: any[]) => any` | Temporary implementation to use | | `callback` | `(electron) => any` | Callback function to execute with temporary implementation | **Returns:** `Promise` - Returns the result of the callback **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); const withImplementationResult = await mockGetName.withImplementation( () => 'temporary mock name', (electron) => electron.app.getName(), ); expect(withImplementationResult).toBe('temporary mock name'); // Async callback const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); const result = await mockGetFileIcon.withImplementation( () => Promise.resolve('temporary mock icon'), async (electron) => await electron.app.getFileIcon('/path/to/icon'), ); expect(result).toBe('temporary mock icon'); ``` ### `getMockImplementation()`[​](#getmockimplementation "Direct link to getmockimplementation") Returns the current mock implementation if there is one. **This call is synchronous** — unlike most mock methods, it doesn't cross the CDP/WebDriver boundary because the implementation function is cached on the outer mock object in the test process. **Signature:** ``` getMockImplementation(): Function | undefined ``` **Returns:** `Function | undefined` - The current mock implementation function, or `undefined` if none is set **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockImplementation(() => 'mocked name'); const mockImpl = mockGetName.getMockImplementation(); expect(mockImpl()).toBe('mocked name'); ``` ### `getMockName()`[​](#getmockname "Direct link to getmockname") Returns the assigned name of the mock. Defaults to `electron..`. **Signature:** ``` getMockName(): string ``` **Returns:** `string` - The mock name **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); expect(mockGetName.getMockName()).toBe('electron.app.getName'); ``` ### `mockName()`[​](#mockname "Direct link to mockname") Assigns a name to the mock. The name can be retrieved via [`getMockName()`](#getmockname). **Signature:** ``` mockName(name: string): ElectronFunctionMock ``` **Parameters:** | Parameter | Type | Description | | --------- | -------- | -------------------------- | | `name` | `string` | Name to assign to the mock | **Returns:** `ElectronFunctionMock` - Returns the mock object for chaining **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); mockGetName.mockName('test mock'); expect(mockGetName.getMockName()).toBe('test mock'); ``` ### `mockReturnThis()`[​](#mockreturnthis "Direct link to mockreturnthis") Useful if you need to return the `this` context from the method without invoking the original implementation. Shorthand for `mockImplementation(function () { return this; })`. Useful for builder-style APIs that chain calls on the same object. **Signature:** ``` mockReturnThis(): Promise ``` **Returns:** `Promise` - Resolves with the mock object for chaining **Example:** ``` // `BrowserWindow.setMenuBarVisibility` is a void method. After mockReturnThis() // it returns the BrowserWindow instance, allowing it to be chained. const mockSetMenuBarVisibility = await browser.electron.mock('BrowserWindow', 'setMenuBarVisibility'); await mockSetMenuBarVisibility.mockReturnThis(); await browser.electron.execute((electron) => { const win = electron.BrowserWindow.getFocusedWindow(); // setMenuBarVisibility now returns `win`, enabling the chained focus() call win.setMenuBarVisibility(false).focus(); }); expect(mockSetMenuBarVisibility).toHaveBeenCalledWith(false); ``` ## Mock Object Properties[​](#mock-object-properties "Direct link to Mock Object Properties") ### `mock.calls`[​](#mockcalls "Direct link to mockcalls") An array containing all arguments for each call. Each item of the array is the arguments of that call. **Type:** ``` Array> ``` **Example:** ``` const mockGetFileIcon = await browser.electron.mock('app', 'getFileIcon'); await browser.electron.execute((electron) => electron.app.getFileIcon('/path/to/icon')); await browser.electron.execute((electron) => electron.app.getFileIcon('/path/to/another/icon', { size: 'small' })); expect(mockGetFileIcon.mock.calls).toStrictEqual([ ['/path/to/icon'], // first call ['/path/to/another/icon', { size: 'small' }], // second call ]); ``` ### `mock.lastCall`[​](#mocklastcall "Direct link to mocklastcall") Contains the arguments of the last call. Returns `undefined` if the mock wasn't called. **Type:** ``` Array | undefined ``` **Example:** ``` const mockSetName = await browser.electron.mock('app', 'setName'); await browser.electron.execute((electron) => electron.app.setName('test')); expect(mockSetName.mock.lastCall).toStrictEqual(['test']); await browser.electron.execute((electron) => electron.app.setName('test 2')); expect(mockSetName.mock.lastCall).toStrictEqual(['test 2']); await browser.electron.execute((electron) => electron.app.setName('test 3')); expect(mockSetName.mock.lastCall).toStrictEqual(['test 3']); ``` ### `mock.results`[​](#mockresults "Direct link to mockresults") An array containing all values that were returned from the mock. Each item is an object with `type` and `value` properties. **Type:** ``` Array<{ type: 'return' | 'throw', value: any }> ``` Available types: * `'return'` - the mock returned without throwing * `'throw'` - the mock threw a value The `value` property contains the returned value or thrown error. If the mock returned a promise, the value will be the resolved value, not the Promise itself, unless it was never resolved. **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); await mockGetName.mockImplementationOnce(() => 'result'); await mockGetName.mockImplementation(() => { throw new Error('thrown error'); }); await expect(browser.electron.execute((electron) => electron.app.getName())).resolves.toBe('result'); await expect(browser.electron.execute((electron) => electron.app.getName())).rejects.toThrow('thrown error'); expect(mockGetName.mock.results).toStrictEqual([ { type: 'return', value: 'result', }, { type: 'throw', value: new Error('thrown error'), }, ]); ``` ### `mock.invocationCallOrder`[​](#mockinvocationcallorder "Direct link to mockinvocationcallorder") The order of mock invocation. Returns an array of numbers that are shared between all defined mocks. Returns an empty array if the mock was never invoked. **Type:** ``` Array ``` **Example:** ``` const mockGetName = await browser.electron.mock('app', 'getName'); const mockGetVersion = await browser.electron.mock('app', 'getVersion'); await browser.electron.execute((electron) => electron.app.getName()); await browser.electron.execute((electron) => electron.app.getVersion()); await browser.electron.execute((electron) => electron.app.getName()); expect(mockGetName.mock.invocationCallOrder).toStrictEqual([1, 3]); expect(mockGetVersion.mock.invocationCallOrder).toStrictEqual([2]); ``` ## Electron Class Mock[​](#electron-class-mock "Direct link to Electron Class Mock") Electron class mocks are returned when calling `browser.electron.mock()` with only a class name (no function name). They provide mocking capabilities for Electron classes like `Tray`, `BrowserWindow`, `Menu`, etc. ### Class Mock Properties[​](#class-mock-properties "Direct link to Class Mock Properties") #### `__constructor`[​](#__constructor "Direct link to __constructor") An [ElectronFunctionMock](#mock-object-methods) object that tracks calls to the class constructor. **Type:** ``` ElectronFunctionMock ``` **Example:** ``` const mockTray = await browser.electron.mock('Tray'); // Track constructor calls await browser.electron.execute((electron) => { new electron.Tray('/path/to/icon.png'); new electron.Tray('/path/to/other-icon.png'); }); expect(mockTray.__constructor).toHaveBeenCalledTimes(2); expect(mockTray.__constructor.mock.calls).toStrictEqual([ ['/path/to/icon.png'], ['/path/to/other-icon.png'], ]); ``` #### `[methodName]`[​](#methodname "Direct link to methodname") All instance methods of the class are available as [ElectronFunctionMock](#mock-object-methods) objects. **Type:** ``` ElectronFunctionMock ``` **Example:** ``` const mockTray = await browser.electron.mock('Tray'); // Mock instance methods await mockTray.setTitle.mockReturnValue(undefined); await mockTray.setToolTip.mockReturnValue(undefined); // Use in tests await browser.electron.execute((electron) => { const tray = new electron.Tray('/path/to/icon.png'); tray.setTitle('My App'); tray.setToolTip('Click for menu'); }); expect(mockTray.setTitle).toHaveBeenCalledWith('My App'); expect(mockTray.setToolTip).toHaveBeenCalledWith('Click for menu'); ``` ### Class Mock Methods[​](#class-mock-methods "Direct link to Class Mock Methods") #### `getMockName()`[​](#getmockname-1 "Direct link to getmockname-1") Returns the assigned name of the class mock. Defaults to `electron.`. **Signature:** ``` getMockName(): string ``` **Returns:** `string` - The mock name **Example:** ``` const mockTray = await browser.electron.mock('Tray'); expect(mockTray.getMockName()).toBe('electron.Tray'); ``` #### `mockRestore()`[​](#mockrestore-1 "Direct link to mockrestore-1") Restores the original Electron class, removing all mocks. **Signature:** ``` mockRestore(): Promise ``` **Returns:** `Promise` **Example:** ``` const mockTray = await browser.electron.mock('Tray'); // Mock some behavior await mockTray.setTitle.mockReturnValue(undefined); // Restore original class await mockTray.mockRestore(); // Original Tray class is now available const tray = await browser.electron.execute((electron) => new electron.Tray('/path/to/icon.png')); expect(tray).toBeDefined(); ``` --- Source: https://webdriver.io/docs/desktop-testing/electron/window-management.md # Window Management The service automatically tracks the active Electron `BrowserWindow` and ensures WebdriverIO commands target it. You can write tests against your app without manually shuffling window handles when the renderer changes (for example, splash screen → main window). ## How It Works[​](#how-it-works "Direct link to How It Works") Before each WebdriverIO command, the service inspects all Electron page targets via Puppeteer. If the active target differs from the one currently selected, it calls `browser.switchToWindow()` on your behalf and records the new handle on `browser.electron.windowHandle`. This runs on the WDIO `beforeCommand` hook, so the switch happens transparently between commands without any explicit setup. ### When the Switch Triggers[​](#when-the-switch-triggers "Direct link to When the Switch Triggers") The service evaluates window state before every command **except** the four that already deal in window state directly: * `getWindowHandle` * `getWindowHandles` * `switchToWindow` * `execute` Internal `browser.electron.execute` calls are also skipped to avoid recursion. ### Multiremote[​](#multiremote "Direct link to Multiremote") In multiremote mode the service evaluates each Electron instance independently. Non-Electron instances (e.g., a Chrome browser running alongside the app) are ignored so they keep their own window state. ## `browser.electron.windowHandle`[​](#browserelectronwindowhandle "Direct link to browserelectronwindowhandle") The currently selected window handle is exposed on the browser: ``` const handle = browser.electron.windowHandle; ``` The service updates it any time it auto-switches windows. You generally don't need to read it directly — it's primarily an internal hook used by `ensureActiveWindowFocus()` to detect changes — but it is useful when debugging unexpected window state. ## Example[​](#example "Direct link to Example") ``` // Test script - the service automatically handles window focus await expect(browser).toHaveTitle('Splash Screen'); // Electron main process - switching a new window splashWindow.hide(); const mainWindow = new BrowserWindow({ /* some options */ }); splashWindow.destroy(); // Test script - the service automatically switches to the new window await expect(browser).toHaveTitle('Main Window'); ``` ## Manual Window Control[​](#manual-window-control "Direct link to Manual Window Control") When you need explicit control (e.g. a popup that should remain open while you assert against the parent), use the standard WebdriverIO window APIs. The service won't fight you — `switchToWindow` is in the exclusion list above, so the next command runs against whatever window you selected. ``` describe('Settings window', () => { it('should save settings in popup window', async () => { // Open settings popup await browser.click('#open-settings-button'); // Get window handles and switch to popup const handles = await browser.getWindowHandles(); expect(handles).toHaveLength(2); // Verify popup opened await browser.switchToWindow(handles[1]); // Modify settings and save await browser.click('#save-settings'); // Return to main window await browser.switchToWindow(handles[0]); }); }); ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### Test commands target the wrong window[​](#test-commands-target-the-wrong-window "Direct link to Test commands target the wrong window") The service decides which window is "active" by asking Puppeteer for all `page` targets and picking the first one that's still valid. When several windows are open simultaneously, that ordering may not match your intent. Use `browser.switchToWindow()` explicitly in those cases. ### `windowHandle` is `undefined`[​](#windowhandle-is-undefined "Direct link to windowhandle-is-undefined") This means Puppeteer reported zero page targets when the service last checked — typically during early startup before the renderer has loaded, or after all windows have been destroyed. Wait for at least one `BrowserWindow` to be ready before issuing renderer-side commands. ### Window focus management disabled warning[​](#window-focus-management-disabled-warning "Direct link to Window focus management disabled warning") A log entry like `Failed to get Puppeteer for instance ..., window focus management disabled` means the service couldn't open a CDP session for that instance (typically a non-Electron multiremote peer). Other instances continue to work; the affected instance simply skips automatic switching. --- Source: https://webdriver.io/docs/desktop-testing/electron/deeplink-testing.md # Deeplink Testing The service provides the ability to test custom protocol handlers and deeplinks in your Electron application using the `browser.electron.triggerDeeplink()` method. This feature automatically handles platform-specific differences, particularly on Windows where deeplinks would normally launch a new instance instead of reaching the test instance. ## Overview[​](#overview "Direct link to Overview") ### What is Deeplink Testing?[​](#what-is-deeplink-testing "Direct link to What is Deeplink Testing?") Deeplink testing allows you to verify that your Electron application correctly handles custom protocol URLs (e.g., `myapp://action?param=value`). This is essential when your app registers as a protocol handler and needs to respond to URLs opened from external sources like web browsers, emails, or other applications. ### Why is it Needed?[​](#why-is-it-needed "Direct link to Why is it Needed?") Testing protocol handlers presents unique challenges: * **Windows Issue**: On Windows, triggering a deeplink normally launches a new app instance instead of routing to the running test instance. This happens because the test instance and the externally-triggered instance use different user data directories. * **Test Automation**: You need a programmatic way to trigger deeplinks without manual intervention. * **Cross-Platform Testing**: Different platforms use different mechanisms to trigger protocol handlers. ### When Should You Use It?[​](#when-should-you-use-it "Direct link to When Should You Use It?") Use `browser.electron.triggerDeeplink()` when you need to: * Test that your app correctly handles custom protocol URLs * Verify deeplink parameter parsing and routing logic * Ensure single-instance behavior works correctly * Test protocol handler registration and activation * Validate deeplink-driven workflows in your application ## Basic Usage[​](#basic-usage "Direct link to Basic Usage") ### Simple Example[​](#simple-example "Direct link to Simple Example") ``` describe('Protocol Handler Tests', () => { it('should handle custom protocol deeplinks', async () => { // Trigger the deeplink await browser.electron.triggerDeeplink('myapp://open?file=test.txt'); // Wait for app to process it await browser.waitUntil(async () => { const openedFile = await browser.electron.execute(() => { return globalThis.lastOpenedFile; }); return openedFile === 'test.txt'; }, { timeout: 5000, timeoutMsg: 'App did not handle the deeplink' }); }); }); ``` ### Complex URL Parameters[​](#complex-url-parameters "Direct link to Complex URL Parameters") The method preserves all URL parameters, including complex query strings: ``` it('should preserve query parameters', async () => { await browser.electron.triggerDeeplink( 'myapp://action?param1=value1¶m2=value2&array[]=a&array[]=b' ); const receivedParams = await browser.electron.execute(() => { return globalThis.lastDeeplinkParams; }); expect(receivedParams.param1).toBe('value1'); expect(receivedParams.param2).toBe('value2'); expect(receivedParams.array).toEqual(['a', 'b']); }); ``` ### Error Handling[​](#error-handling "Direct link to Error Handling") ``` it('should reject invalid protocols', async () => { await expect( browser.electron.triggerDeeplink('https://example.com') ).rejects.toThrow('Invalid deeplink protocol'); }); it('should reject malformed URLs', async () => { await expect( browser.electron.triggerDeeplink('not a url') ).rejects.toThrow('Invalid deeplink URL'); }); ``` ## Platform Behavior[​](#platform-behavior "Direct link to Platform Behavior") The service handles platform-specific differences automatically: ### Windows[​](#windows "Direct link to Windows") **Behavior:** * Uses `cmd /c start` command to trigger the deeplink * Automatically appends the test instance's `userData` directory as a query parameter * Cannot use script-based apps (`appEntryPoint`) - requires packaged binary **URL Modification:** ``` // Input URL 'myapp://test?foo=bar' // URL triggered on Windows (userData appended automatically) 'myapp://test?foo=bar&userData=/tmp/electron-test' ``` **Why This is Needed:** On Windows, when a protocol URL is opened, the OS launches the registered application binary. Without the userData parameter, this creates a new instance with a different user data directory, preventing Electron's single-instance lock from working correctly. By appending the userData parameter, your app can use the same directory as the test instance, allowing the single-instance lock to route the deeplink to the test instance. ### macOS[​](#macos "Direct link to macOS") **Behavior:** * Uses `open` command to trigger the deeplink * No URL modification needed (OS handles single-instance automatically) * No special configuration required **URL Modification:** ``` // URL passed unchanged 'myapp://test?foo=bar' ``` ### Linux[​](#linux "Direct link to Linux") **Behavior:** * Uses `gio open` command to trigger the deeplink * Automatically appends the test instance's `userData` directory as a query parameter (like Windows) * Cannot use script-based apps (`appEntryPoint`) - requires packaged binary **URL Modification:** ``` // Input URL 'myapp://test?foo=bar' // URL triggered on Linux (userData appended automatically) 'myapp://test?foo=bar&userData=/tmp/electron-test' ``` **Why This is Needed:** Similar to Windows, Linux requires the userData parameter to ensure the deeplink-triggered instance uses the same user data directory as the test instance, enabling Electron's single-instance lock to route the deeplink correctly. ## Setup Requirements[​](#setup-requirements "Direct link to Setup Requirements") ### 1. Service Configuration[​](#1-service-configuration "Direct link to 1. Service Configuration") #### Windows & Linux Configuration[​](#windows--linux-configuration "Direct link to Windows & Linux Configuration") On Windows and Linux, you **must use a packaged binary** (not `appEntryPoint`). Script-based apps cannot register protocol handlers at the OS level. *`wdio.conf.ts`* ``` export const config = { capabilities: [ { browserName: 'electron', 'wdio:electronServiceOptions': { // Use packaged binary (auto-detected or explicit) appBinaryPath: './dist/win-unpacked/MyApp.exe', // Optional but recommended: Explicit user data directory appArgs: ['--user-data-dir=/tmp/test-user-data'] } } ] }; ``` **Important Notes:** * `appEntryPoint` will NOT work for protocol handler testing on Windows/Linux * You must use `appBinaryPath` or let the service auto-detect your binary * The service will warn you if you're using `appEntryPoint` with protocol handlers * See [Service Configuration](/docs/desktop-testing/electron/configuration.md#appbinarypath) for help finding your app binary path #### macOS Configuration[​](#macos-configuration "Direct link to macOS Configuration") macOS works with both packaged binaries and script-based apps: *`wdio.conf.ts`* ``` export const config = { capabilities: [ { browserName: 'electron', 'wdio:electronServiceOptions': { // Either works on macOS appBinaryPath: './dist/mac/MyApp.app/Contents/MacOS/MyApp', // OR appEntryPoint: './dist/main.js' } } ] }; ``` ### 2. Protocol Handler Registration[​](#2-protocol-handler-registration "Direct link to 2. Protocol Handler Registration") Your app must register as a protocol handler. This is typically done in your main process: ``` import { app } from 'electron'; // Register protocol handler if (process.defaultApp) { // Development: Include path to main file app.setAsDefaultProtocolClient('myapp', process.execPath, [ path.resolve(process.argv[1]) ]); } else { // Production: No additional arguments needed app.setAsDefaultProtocolClient('myapp'); } ``` **Note:** Replace `'myapp'` with your custom protocol scheme. ### 3. Single Instance Lock[​](#3-single-instance-lock "Direct link to 3. Single Instance Lock") Your app must implement single-instance lock to receive deeplinks: ``` import { app } from 'electron'; const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { // Another instance is running, quit this one app.quit(); } else { // This is the primary instance, handle second-instance events app.on('second-instance', (event, commandLine, workingDirectory) => { // Focus window if minimized if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } // Handle the deeplink from commandLine const url = commandLine.find(arg => arg.startsWith('myapp://')); if (url) { handleDeeplink(url); } }); } ``` ## App Implementation[​](#app-implementation "Direct link to App Implementation") ### Complete Example (All Platforms)[​](#complete-example-all-platforms "Direct link to Complete Example (All Platforms)") Here's a complete implementation that works on Windows, macOS, and Linux: *`main.ts`* ``` import { app, BrowserWindow } from 'electron'; import path from 'path'; // ===== WINDOWS & LINUX: Parse userData from deeplink (MUST be before app.ready) ===== if (process.platform === 'win32' || process.platform === 'linux') { const url = process.argv.find(arg => arg.startsWith('myapp://')); if (url) { try { const parsed = new URL(url); const userDataPath = parsed.searchParams.get('userData'); if (userDataPath) { // Set user data directory to match test instance app.setPath('userData', userDataPath); } } catch (error) { console.error('Failed to parse deeplink URL:', error); } } } // ===== Single Instance Lock ===== const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { app.quit(); } else { app.on('second-instance', (event, commandLine, workingDirectory) => { // Focus the main window if it exists if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } // Find and handle deeplink from command line const url = commandLine.find(arg => arg.startsWith('myapp://')); if (url) { handleDeeplink(url); } }); // Standard app initialization app.whenReady().then(createWindow); } // ===== Protocol Handler Registration ===== if (process.defaultApp) { app.setAsDefaultProtocolClient('myapp', process.execPath, [ path.resolve(process.argv[1]) ]); } else { app.setAsDefaultProtocolClient('myapp'); } // ===== Application Setup ===== let mainWindow: BrowserWindow | null = null; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: false, contextIsolation: true } }); mainWindow.loadFile('index.html'); // Handle deeplink on macOS (open-url event) app.on('open-url', (event, url) => { event.preventDefault(); handleDeeplink(url); }); // Handle initial deeplink on Windows/Linux (from argv) const url = process.argv.find(arg => arg.startsWith('myapp://')); if (url) { handleDeeplink(url); } } // ===== Deeplink Handler ===== function handleDeeplink(url: string) { console.log('Received deeplink:', url); try { const parsed = new URL(url); // IMPORTANT: Remove userData parameter before processing // (This parameter is only for Windows single-instance routing) parsed.searchParams.delete('userData'); const cleanUrl = parsed.toString(); // Store for test verification (optional) if (!globalThis.receivedDeeplinks) { globalThis.receivedDeeplinks = []; } globalThis.receivedDeeplinks.push(cleanUrl); // Your actual deeplink handling logic here const action = parsed.hostname; // e.g., 'open' from 'myapp://open' const params = Object.fromEntries(parsed.searchParams); switch (action) { case 'open': // Handle 'myapp://open?file=...' if (params.file) { openFile(params.file); } break; case 'action': // Handle 'myapp://action?...' performAction(params); break; default: console.warn('Unknown deeplink action:', action); } // Notify renderer process if needed if (mainWindow) { mainWindow.webContents.send('deeplink-received', cleanUrl); } } catch (error) { console.error('Failed to parse deeplink:', error); } } function openFile(filePath: string) { console.log('Opening file:', filePath); // Your file opening logic } function performAction(params: Record) { console.log('Performing action with params:', params); // Your action logic } ``` ## Common Issues[​](#common-issues "Direct link to Common Issues") ### Deeplink Launches New Instance (Windows/Linux)[​](#deeplink-launches-new-instance-windowslinux "Direct link to Deeplink Launches New Instance (Windows/Linux)") **Symptom:** On Windows or Linux, triggering a deeplink creates a new application instance instead of routing to the test instance. **Cause:** The test instance and the deeplink-triggered instance are using different user data directories, preventing Electron's single-instance lock from working. **Solution:** 1. Ensure you're using a packaged binary (not `appEntryPoint`) in your WDIO configuration 2. Verify your app parses the `userData` parameter on Windows and Linux: ``` if (process.platform === 'win32' || process.platform === 'linux') { const url = process.argv.find(arg => arg.startsWith('myapp://')); if (url) { const parsed = new URL(url); const userDataPath = parsed.searchParams.get('userData'); if (userDataPath) { app.setPath('userData', userDataPath); } } } ``` 3. Make sure this code runs **before** `app.whenReady()` or any other app initialization For more details, see the [Common Issues guide](/docs/desktop-testing/electron/common-issues.md). ### Warning: "Using appEntryPoint with protocol handlers"[​](#warning-using-appentrypoint-with-protocol-handlers "Direct link to Warning: \"Using appEntryPoint with protocol handlers\"") **Symptom:** You see a warning in your test logs about using `appEntryPoint` with protocol handlers on Windows or Linux. **Cause:** Protocol handlers on Windows and Linux require a registered executable binary at the OS level. Script-based apps (`appEntryPoint`) cannot register as protocol handlers. **Solution:** Use `appBinaryPath` (or let the service auto-detect it) instead of `appEntryPoint`: ``` // Before (doesn't work for protocol handlers on Windows/Linux) 'wdio:electronServiceOptions': { appEntryPoint: './dist/main.js' } // After (works correctly) 'wdio:electronServiceOptions': { appBinaryPath: './dist/linux-unpacked/MyApp' // OR let the service auto-detect your binary } ``` ### Warning: "No user data directory detected"[​](#warning-no-user-data-directory-detected "Direct link to Warning: \"No user data directory detected\"") **Symptom:** You see a warning about missing user data directory. **Cause:** The service couldn't detect a user data directory from your app configuration. **Solution:** Explicitly set the user data directory in your app args: ``` 'wdio:electronServiceOptions': { appBinaryPath: './dist/win-unpacked/MyApp.exe', appArgs: ['--user-data-dir=/tmp/my-test-user-data'] } ``` ### Invalid Deeplink Protocol Error[​](#invalid-deeplink-protocol-error "Direct link to Invalid Deeplink Protocol Error") **Symptom:** Error: "Invalid deeplink protocol: https. Expected a custom protocol." **Cause:** You're trying to use `triggerDeeplink()` with http/https/file protocols, which aren't custom protocols. **Solution:** Only use custom protocol schemes: ``` // Correct - custom protocol await browser.electron.triggerDeeplink('myapp://action'); // Incorrect - web protocol await browser.electron.triggerDeeplink('https://example.com'); // Throws error // Incorrect - file protocol await browser.electron.triggerDeeplink('file:///path/to/file'); // Throws error ``` ### Deeplinks Not Received in App[​](#deeplinks-not-received-in-app "Direct link to Deeplinks Not Received in App") **Symptom:** The deeplink is triggered but your app doesn't receive it. **Possible Causes and Solutions:** 1. **Protocol not registered:** * Verify `app.setAsDefaultProtocolClient()` is called * Check your app's package.json has correct protocol configuration 2. **Missing second-instance handler:** * Ensure you've implemented `app.on('second-instance', ...)` handler * Verify the handler is checking for your protocol in `commandLine` 3. **macOS open-url handler missing:** * Add `app.on('open-url', ...)` handler for macOS * Call `event.preventDefault()` in the handler 4. **Deeplink parsed incorrectly:** * Check console logs to see if the URL is being received * Verify URL parsing logic handles your URL format ### Timing Issues[​](#timing-issues "Direct link to Timing Issues") **Symptom:** Tests fail intermittently because the app hasn't processed the deeplink yet. **Solution:** Always use `waitUntil` to wait for the app to process the deeplink: ``` await browser.electron.triggerDeeplink('myapp://action'); // Wait for app to process await browser.waitUntil(async () => { const processed = await browser.electron.execute(() => { return globalThis.deeplinkProcessed; }); return processed === true; }, { timeout: 5000, timeoutMsg: 'App did not process the deeplink within 5 seconds' }); ``` --- Source: https://webdriver.io/docs/desktop-testing/electron/standalone.md # Standalone Mode You can also use the service without the WDIO testrunner, e.g. in a normal Node.js script. The `startWdioSession` method accepts `ElectronServiceCapabilities`, which are the capabilities specified in a regular [WDIO configuration](/docs/desktop-testing/electron/configuration.md). The method creates a new WDIO session using your configuration and returns the WebdriverIO browser object: ``` import { startWdioSession } from '@wdio/electron-service'; const browser = await startWdioSession([{ 'browserName': 'electron', // you need to specify browserName 'browserVersion': '33.2.1', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/binary', }, 'goog:chromeOptions': { args: ['--disable-dev-shm-usage', '--disable-gpu', '--headless'], }, 'wdio:chromedriverOptions': { binary: '/path/to/chromedriver', }, }]); const appName = await browser.electron.execute((electron) => electron.app.getName()); ``` You can also use the `createElectronCapabilities` helper to build capabilities programmatically: ``` import { startWdioSession, createElectronCapabilities } from '@wdio/electron-service'; const caps = createElectronCapabilities({ appBinaryPath: '/path/to/binary', appArgs: ['--disable-dev-shm-usage', '--disable-gpu', '--headless'], }); const browser = await startWdioSession([caps]); ``` `rootDir` can be specified in the second (optional) `ElectronServiceGlobalOptions` parameter, which also accepts mocking preferences for the session: ``` const browser = await startWdioSession([ { ... }, { rootDir: '/path/to/dir', clearMocks: false, resetMocks: false, restoreMocks: true, } ]); ``` ## Log Capture in Standalone Mode[​](#log-capture-in-standalone-mode "Direct link to Log Capture in Standalone Mode") Standalone mode supports capturing console logs from both main and renderer processes. Unlike test runner mode where logs are forwarded to WDIO's logger, standalone mode writes logs to timestamped files. ### Basic Log Capture[​](#basic-log-capture "Direct link to Basic Log Capture") ``` import { startWdioSession, cleanupWdioSession } from '@wdio/electron-service'; const browser = await startWdioSession([{ browserName: 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/binary', captureMainProcessLogs: true, captureRendererLogs: true, mainProcessLogLevel: 'info', rendererLogLevel: 'info', logDir: './test-logs' // Required for standalone mode } }]); // Execute code in the main process - logs will be captured with [Electron:MainProcess] prefix await browser.electron.execute((electron) => { console.log('Application initialized'); console.info('App name:', electron.app.getName()); console.warn('Using deprecated API in production build'); }); // Execute code in the renderer process - logs will be captured with [Electron:Renderer] prefix await browser.execute(() => { console.log('Page loaded successfully'); console.debug('Window dimensions:', window.innerWidth, window.innerHeight); console.error('Failed to fetch user data from API'); }); // Cleanup - closes log file await cleanupWdioSession(browser); ``` ### Log File Output[​](#log-file-output "Direct link to Log File Output") Logs are written to `{logDir}/wdio-{timestamp}.log`: ``` 2025-12-29T19:07:00.123Z INFO electron-service:service: [Electron:MainProcess] Application initialized 2025-12-29T19:07:00.234Z INFO electron-service:service: [Electron:MainProcess] App name: MyElectronApp 2025-12-29T19:07:00.456Z WARN electron-service:service: [Electron:MainProcess] Using deprecated API in production build 2025-12-29T19:07:01.123Z INFO electron-service:service: [Electron:Renderer] Page loaded successfully 2025-12-29T19:07:01.234Z DEBUG electron-service:service: [Electron:Renderer] Window dimensions: 1920 1080 2025-12-29T19:07:01.456Z ERROR electron-service:service: [Electron:Renderer] Failed to fetch user data from API ``` ### Log Level Filtering[​](#log-level-filtering "Direct link to Log Level Filtering") Control which logs are captured by setting minimum log levels: ``` const browser = await startWdioSession([{ browserName: 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/binary', captureMainProcessLogs: true, mainProcessLogLevel: 'warn', // Only warn and error captureRendererLogs: true, rendererLogLevel: 'debug', // Debug, info, warn, and error logDir: './logs' } }]); ``` ### Reading Logs Programmatically[​](#reading-logs-programmatically "Direct link to Reading Logs Programmatically") ``` import { readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; // After test execution const logDir = './test-logs'; const logFiles = readdirSync(logDir).filter(f => f.startsWith('wdio-')); const latestLog = logFiles.sort().reverse()[0]; const logContent = readFileSync(join(logDir, latestLog), 'utf-8'); // Parse or analyze logs const mainProcessLogs = logContent .split('\n') .filter(line => line.includes('[Electron:MainProcess]')); ``` ### Important Notes[​](#important-notes "Direct link to Important Notes") * **`logDir` is required**: Logs cannot be captured in standalone mode without specifying `logDir` * **Automatic cleanup**: Call `cleanupWdioSession()` to ensure log files are properly closed * **CDP requirements**: * **Main process logs**: Require the `EnableNodeCliInspectArguments` fuse to be enabled * **Renderer process logs**: Work independently via Puppeteer, no fuse requirement * If the CDP bridge is unavailable, only main process logs will be disabled (renderer logs continue to work) * **No WDIO logger**: In standalone mode, logs are written to files, not forwarded to WDIO's logger --- Source: https://webdriver.io/docs/desktop-testing/electron/debugging.md # Debugging This guide covers the debugging tools and features available in the Electron service to help you gain visibility into your application's behavior during tests. For configuration reference, see [Service Configuration](/docs/desktop-testing/electron/configuration.md). For troubleshooting specific errors, see [Common Issues](/docs/desktop-testing/electron/common-issues.md). ## Debug Logging[​](#debug-logging "Direct link to Debug Logging") If you need extra insight into what the service is doing you can enable namespaced debug logging via the `DEBUG` environment variable. * `DEBUG=wdio-electron-service` is equivalent to `DEBUG=wdio-electron-service:*` (enable all service namespaces) * You can target specific areas, e.g. `DEBUG=wdio-electron-service:service,mock` > **Migrating from v9?** The debug namespace **did not change** with the v10 package rename. Continue to use `wdio-electron-service:*` rather than `@wdio/electron-service:*` — the colon separator inside the namespace is what `debug` parses, so the unscoped form is preserved deliberately. Examples: ``` # enable all service logs DEBUG=wdio-electron-service:* wdio run ./wdio.conf.ts # enable only core service + mocks DEBUG=wdio-electron-service:service,mock wdio run ./wdio.conf.ts ``` Logs are also forwarded into WDIO runner logs under your configured `outputDir`. This is utilising the [`debug`](https://github.com/debug-js/debug) logging package. ## Electron Log Capture[​](#electron-log-capture "Direct link to Electron Log Capture") The service can capture console output from both Electron's main process and renderer processes. ### Enabling Log Capture[​](#enabling-log-capture "Direct link to Enabling Log Capture") ``` export const config = { services: [ ['electron', { captureMainProcessLogs: true, captureRendererLogs: true, mainProcessLogLevel: 'info', rendererLogLevel: 'info' }] ] }; ``` Logs will appear in your WDIO test output with appropriate prefixes: ``` [Electron:MainProcess] Database connection established [Electron:Renderer] Component mounted successfully [Electron:MainProcess] IPC message received: user-action ``` ### Log Levels[​](#log-levels "Direct link to Log Levels") Filter logs by setting minimum levels. Log priority (lowest to highest): ``` trace < debug < info < warn < error ``` Examples: ``` // Capture only warnings and errors from main process mainProcessLogLevel: 'warn' // Capture debug and above from renderer (excludes trace) rendererLogLevel: 'debug' // Capture everything from main process mainProcessLogLevel: 'trace' ``` ### Debugging with Logs[​](#debugging-with-logs "Direct link to Debugging with Logs") **Scenario 1: IPC Communication Issues** Enable main process logs to see IPC handler execution: ``` // In main process ipcMain.handle('user-action', async (event, data) => { console.log('[IPC] Received user-action:', data); const result = await processAction(data); console.log('[IPC] Sending response:', result); return result; }); ``` Test output: ``` [Electron:MainProcess] [IPC] Received user-action: { type: 'save' } [Electron:MainProcess] [IPC] Sending response: { success: true } ``` **Scenario 2: Renderer Lifecycle Issues** Enable renderer logs to debug component initialization: ``` // In renderer console.log('[Lifecycle] App component mounting'); console.log('[Lifecycle] Loading user data'); console.log('[Lifecycle] Render complete'); ``` **Scenario 3: Crash Investigation** Set log level to `debug` or `trace` to capture detailed diagnostic information: ``` export const config = { services: [ ['electron', { captureMainProcessLogs: true, mainProcessLogLevel: 'debug', // Capture detailed logs captureRendererLogs: true, rendererLogLevel: 'debug' }] ] }; ``` ### Log Capture Requirements[​](#log-capture-requirements "Direct link to Log Capture Requirements") **Main Process Logs:** * Require the `EnableNodeCliInspectArguments` Electron fuse to be enabled * Require CDP bridge connection to main process * If the CDP bridge is unavailable: * ⚠️ Main process log capture will be disabled with a warning * ⚠️ Warning visible with `DEBUG=wdio-electron-service:*` * ✅ Tests continue normally - no failures * See [Common Issues - CDP bridge initialization](/docs/desktop-testing/electron/common-issues.md#cdp-bridge-cannot-be-initialized-enablenodecliinspectarguments-fuse-is-disabled) for troubleshooting **Renderer Process Logs:** * Use Puppeteer CDP sessions - work independently of main process CDP bridge * Do NOT require the `EnableNodeCliInspectArguments` fuse * Will continue to work even if main process CDP bridge is unavailable * Useful for debugging when the fuse is disabled ### Standalone Mode Logging[​](#standalone-mode-logging "Direct link to Standalone Mode Logging") When using `startWdioSession()` without the WDIO test runner, logs are written to files instead of being forwarded to WDIO's logger: ``` const browser = await startWdioSession([{ browserName: 'electron', 'wdio:electronServiceOptions': { appBinaryPath: '/path/to/binary', captureMainProcessLogs: true, logDir: './test-logs' // Required for standalone mode } }]); ``` See [Standalone Mode documentation](/docs/desktop-testing/electron/standalone.md#log-capture-in-standalone-mode) for details. --- Source: https://webdriver.io/docs/desktop-testing/electron/common-issues.md # Common Issues These are some common issues which others have encountered whilst using the service. For debugging tools and features, see the [Debugging guide](/docs/desktop-testing/electron/debugging.md). ## CDP bridge cannot be initialized: EnableNodeCliInspectArguments fuse is disabled[​](#cdp-bridge-cannot-be-initialized-enablenodecliinspectarguments-fuse-is-disabled "Direct link to CDP bridge cannot be initialized: EnableNodeCliInspectArguments fuse is disabled") This warning appears when your Electron app has the `EnableNodeCliInspectArguments` fuse explicitly disabled. The CDP (Chrome DevTools Protocol) bridge relies on the `--inspect` flag to connect to Electron's main process, so when this fuse is disabled, the service cannot provide access to the main process APIs. #### Impact[​](#impact "Direct link to Impact") When this fuse is disabled: * ❌ `browser.electron.execute()` - main process API access will not work * ❌ `browser.electron.mock()` - mocking main process APIs will not work * ❌ Main process log capture will not work (see [Debugging - Log Capture Requirements](/docs/desktop-testing/electron/debugging.md#log-capture-requirements)) * ✅ Renderer process testing continues to work normally * ✅ Renderer process log capture continues to work (uses Puppeteer, not CDP bridge) * ✅ Service initialization continues normally - no crashes or failures * ✅ Clear error messages when attempting to use disabled APIs #### Solution[​](#solution "Direct link to Solution") Enable the fuse in your test builds. If you're disabling this fuse for production (which is good security practice), use conditional configuration: ``` import { flipFuses, FuseVersion, FuseV1Options } from '@electron/fuses'; await flipFuses(require('electron'), { version: FuseVersion.V1, [FuseV1Options.EnableNodeCliInspectArguments]: process.env.BUILD_FOR_TESTS === 'true', // ... other fuses }); ``` Then build with the environment variable, e.g.: ``` BUILD_FOR_TESTS=true npm run build # for testing npm run build # for production ``` See: [Electron Fuses Documentation](https://www.electronjs.org/docs/latest/tutorial/fuses#nodecliinspect) ## DevToolsActivePort file doesn't exist[​](#devtoolsactiveport-file-doesnt-exist "Direct link to DevToolsActivePort file doesn't exist") This is a Chromium error which may appear when using Docker or CI. Most of the "fixes" discussed online are based around passing different combinations of args to Chromium - you can set these via [`appArgs`](/docs/desktop-testing/electron/configuration.md#appargs), though in most cases using xvfb has proven to be more effective; the service itself uses xvfb when running E2Es on Linux CI. See this [WDIO documentation page](https://webdriver.io/docs/headless-and-xvfb) for instructions on how to set up xvfb. **Note:** WebdriverIO 9.19.1+ is required for automatic Xvfb support via the `autoXvfb` configuration option. For legacy WDIO versions, you'll need to use external tools like `xvfb-maybe` or manually set up Xvfb. ### Failed to create session. session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir[​](#failed-to-create-session-session-not-created-probably-user-data-directory-is-already-in-use-please-specify-a-unique-value-for---user-data-dir-argument-or-dont-use---user-data-dir "Direct link to Failed to create session. session not created: probably user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir") This is another obscure Chromium error which, despite the message, is usually not fixed by providing a unique `--user-data-dir` value. In the Electron context this usually occurs when the Electron app crashes during or shortly after initialization. WDIO / ChromeDriver attempts to reconnect, starting a new electron instance, which attempts to use the same user-data-dir path. Whilst there may be other causes, on Linux this is often fixed with xvfb. See this [WDIO documentation page](https://webdriver.io/docs/headless-and-xvfb) for instructions on how to set up xvfb. **Note:** WebdriverIO 9.19.1+ is required for automatic Xvfb support via the `autoXvfb` configuration option. For legacy WDIO versions, you'll need to use external tools like `xvfb-maybe` or manually set up Xvfb. ### All versions of Electron fail to open on Ubuntu 24.04+[​](#all-versions-of-electron-fail-to-open-on-ubuntu-2404 "Direct link to All versions of Electron fail to open on Ubuntu 24.04+") See [this issue](https://github.com/electron/electron/issues/41066) for more details. This is caused by AppArmor restrictions on unprivileged user namespaces. #### Recommended Solution: Automatic AppArmor Profile[​](#recommended-solution-automatic-apparmor-profile "Direct link to Recommended Solution: Automatic AppArmor Profile") The service can automatically create and install a custom AppArmor profile for your Electron binary. Enable this feature by setting the `apparmorAutoInstall` option: ``` export const config = { // ... services: [ [ 'electron', { apparmorAutoInstall: 'sudo' // or true if running as root } ] ], // OR configure it per capability: capabilities: [ { 'browserName': 'electron', 'wdio:electronServiceOptions': { apparmorAutoInstall: 'sudo' } } ] }; ``` * `'sudo'`: Install if root or via non-interactive sudo (`sudo -n`) if available * `true`: Install only if running as root (no sudo) * `false` (default): Never install; warn and continue without AppArmor profile #### Alternative Solution[​](#alternative-solution "Direct link to Alternative Solution") **Manual AppArmor workaround**: Run `sysctl -w kernel.apparmor_restrict_unprivileged_userns=0` before running your tests. This command requires root privileges; if necessary, run it as the root user or use the `sudo` command. ### TypeError: logger is not a function[​](#typeerror-logger-is-not-a-function "Direct link to TypeError: logger is not a function") > Still applies in v10. The package was renamed from `wdio-electron-service` to `@wdio/electron-service`, but the import-time initialization order didn't change — the same workaround is needed. This error occurs when importing the `browser` object directly at the top level of test files: ``` // ❌ This may cause "TypeError: logger is not a function" import { browser } from "@wdio/electron-service"; describe("My Tests", () => { it("should work", async () => { await browser.electron.execute(/* ... */); }); }); ``` The service's internal logger and other dependencies aren't fully initialized when the browser object is imported during the test file loading phase, before WebDriverIO services have completed their initialization. The solution is to use dynamic import within a `before` hook to ensure the service is fully initialized: ``` // ✅ Correct approach - dynamic import in before hook import type { Mock } from "@vitest/spy"; import { $, expect } from "@wdio/globals"; import type { browser as WdioBrowser } from "@wdio/electron-service"; let browser: typeof WdioBrowser; describe("My Tests", () => { before(async () => { ({ browser } = await import("@wdio/electron-service")); }); it("should work", async () => { await browser.electron.execute(/* ... */); }); }); ``` **Note for Service Contributors:** If you're working within the desktop-mobile repository itself, you can use pnpm overrides to link to the workspace version: ``` { "pnpm": { "overrides": { "@wdio/electron-service": "workspace:*" } } } ``` This allows direct imports to work reliably within the service's own repository, but this approach only applies when developing the service itself. --- Source: https://webdriver.io/docs/desktop-testing/tauri.md # Tauri [Tauri](https://tauri.app/) is a framework for building lightweight, secure cross-platform desktop applications using a Rust backend and the operating system's native webview. WebdriverIO's Tauri service automates the discovery, launch, and driving of Tauri apps on Windows (WebView2), macOS (WKWebView), and Linux (WebKitGTK) so the same test suite works everywhere. The advantages of using WebdriverIO for testing Tauri applications are: * 🚗 auto-provisioning of the WebDriver layer — choose `tauri-driver`, the CrabNebula driver, or the in-app embedded plugin * 📦 cross-platform binary detection (Edge WebView2 driver bundled on Windows) * 🧩 optional `@wdio/tauri-plugin` for richer in-webview integration (`browser.tauri.execute`, mocking) * 🔗 deeplink + protocol handler testing * 🪵 forwarding of Rust + frontend logs into the WebdriverIO test reporter ## Getting Started[​](#getting-started "Direct link to Getting Started") To initiate a new WebdriverIO project, run: ``` npm create wdio@latest ./ ``` When the wizard asks what type of testing you'd like to do, select *"Desktop Testing - of Electron, Tauri, or macOS Applications"*, then choose *Tauri* at the framework prompt. The wizard will then ask which WebDriver provider you want to use (official `tauri-driver`, CrabNebula, or the embedded plugin) and whether you'd like the optional `@wdio/tauri-plugin` for richer integration. The wizard installs the npm packages automatically and prints any required Cargo additions to stdout for you to paste into your `src-tauri/Cargo.toml`. ## Manual Setup[​](#manual-setup "Direct link to Manual Setup") If you already have a WebdriverIO project, install the service: ``` npm install --save-dev @wdio/tauri-service # optional: richer in-webview integration npm install --save-dev @wdio/tauri-plugin ``` For the embedded WebDriver plugin (recommended — runs the W3C server inside your app, no external `tauri-driver` needed), add the Cargo crate to `src-tauri/Cargo.toml`: ``` [dependencies] tauri-plugin-wdio-webdriver = "1" ``` …and register it in `src-tauri/src/lib.rs`: ``` tauri::Builder::default() .plugin(tauri_plugin_wdio_webdriver::init()) // ... ``` Then add the service to your config: ``` // wdio.conf.ts export const config: WebdriverIO.Config = { // ... services: [['tauri', { appBinaryPath: './src-tauri/target/release/my-tauri-app', driverProvider: 'embedded' }]] } ``` That's it 🎉 Learn more about [configuring the Tauri Service](/docs/desktop-testing/tauri/configuration.md), [the Tauri plugin setup](/docs/desktop-testing/tauri/plugin-setup.md), [platform-specific notes](/docs/desktop-testing/tauri/platform-support.md), and [common usage patterns](/docs/desktop-testing/tauri/usage-examples.md). --- Source: https://webdriver.io/docs/desktop-testing/tauri/quick-start.md # Quick Start Get up and running with WebdriverIO and Tauri E2E testing in minutes. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") ### Required Software[​](#required-software "Direct link to Required Software") 1. **Node.js 18+** - Download from [nodejs.org](https://nodejs.org) 2. **Rust Toolchain** - Required for building Tauri apps and tauri-driver ``` curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` 3. **Tauri CLI** - Install globally or as dev dependency ``` npm install -g @tauri-apps/cli # or cargo install tauri-cli ``` ### Platform-Specific Requirements[​](#platform-specific-requirements "Direct link to Platform-Specific Requirements") #### Windows[​](#windows "Direct link to Windows") * **Microsoft Visual C++ Build Tools** - Download from [Microsoft Visual C++](https://visualstudio.microsoft.com/visual-cpp-build-tools/) * **Edge WebDriver** - Auto-managed by the service (see [Edge WebDriver Windows](/docs/desktop-testing/tauri/edge-webdriver-windows.md)) #### Linux[​](#linux "Direct link to Linux") * **WebKitGTK Development Libraries** - Install WebKitWebDriver ``` # Debian/Ubuntu sudo apt-get install -y webkit2gtk-driver # Fedora 40+ sudo dnf install -y webkit2gtk-driver # Arch Linux sudo pacman -S webkit2gtk-4.1 # Void Linux sudo xbps-install -y webkit2gtk-devel ``` See [Platform Support](/docs/desktop-testing/tauri/platform-support.md) for detailed distribution support information. #### macOS[​](#macos "Direct link to macOS") ✅ **Supported** - Use the embedded WebDriver provider (`driverProvider: 'embedded'`) for native macOS testing without external dependencies. See [Platform Support](/docs/desktop-testing/tauri/platform-support.md) for details. ## Setting Up a Tauri App[​](#setting-up-a-tauri-app "Direct link to Setting Up a Tauri App") ### Fastest Way: Use Tauri CLI[​](#fastest-way-use-tauri-cli "Direct link to Fastest Way: Use Tauri CLI") ``` npm create tauri-app@latest ``` Follow the prompts and select your preferred frontend framework. ### Manual Setup[​](#manual-setup "Direct link to Manual Setup") Create a minimal Tauri app: ``` mkdir my-tauri-app cd my-tauri-app # Create frontend (use any framework or plain HTML) mkdir src echo '

Hello, Tauri!

' > src/index.html # Create Rust backend cargo init --name my_app src-tauri cd src-tauri # Add Tauri to Cargo.toml # [dependencies] # tauri = { version = "2.9", features = ["shell-open"] } # tauri-build = "2.0" ``` ### Essential Files[​](#essential-files "Direct link to Essential Files") Create the minimal required files for a Tauri app: **`src-tauri/src/main.rs`** ``` #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { tauri::Builder::default() .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` **`src-tauri/tauri.conf.json`** ``` { "$schema": "https://schema.tauri.app/config/2", "productName": "my-app", "version": "0.1.0", "identifier": "com.mycompany.myapp", "build": { "frontendDist": "../src", "beforeDevCommand": "echo 'dev server running'", "beforeBuildCommand": "echo 'building frontend'" }, "app": { "withGlobalTauri": true, "windows": [ { "title": "My App", "width": 800, "height": 600 } ] } } ``` **`src-tauri/Cargo.toml`** - Add: ``` [dependencies] tauri = { version = "2", features = [] } tauri-plugin-wdio = "1" [build-dependencies] tauri-build = "2" ``` **`src-tauri/build.rs`** ``` fn main() { tauri_build::build() } ``` ## Tauri Plugin Setup[​](#tauri-plugin-setup "Direct link to Tauri Plugin Setup") ⚠️ **The tauri-plugin-wdio is required for testing** - Skip this section only if you want basic WebDriver operations without mocking or log capture. ### Complete Plugin Setup[​](#complete-plugin-setup "Direct link to Complete Plugin Setup") 1. **Already added to Cargo.toml** (see above) 2. **Register in `src-tauri/src/main.rs`** ``` fn main() { tauri::Builder::default() .plugin(tauri_plugin_wdio::init()) // Add this line .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` 3. **Create `src-tauri/capabilities/default.json`** ``` { "identifier": "default", "windows": ["main"], "permissions": [ "core:default", "core:window:default", "wdio:default" ] } ``` 4. **Import frontend plugin in `src/index.html`** ``` My App

Hello, Tauri!

``` For detailed plugin setup and troubleshooting, see [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md). ## Building the Tauri App[​](#building-the-tauri-app "Direct link to Building the Tauri App") ``` # Build for release (required for testing with WebdriverIO) cd src-tauri cargo build --release ``` On macOS/Linux, you'll also need to give the app executable permissions: ``` chmod +x target/release/my_app # Linux/macOS # or on Windows: # target\release\my_app.exe ``` ## WebdriverIO Installation[​](#webdriverio-installation "Direct link to WebdriverIO Installation") ### 1. Install WebdriverIO[​](#1-install-webdriverio "Direct link to 1. Install WebdriverIO") ``` npm install --save-dev @wdio/cli @wdio/tauri-service ``` ### 2. Initialize Configuration[​](#2-initialize-configuration "Direct link to 2. Initialize Configuration") Use the WebdriverIO CLI setup wizard: ``` npx wdio config ``` Or manually create `wdio.conf.ts`: ``` export const config = { runner: 'local', specs: ['./test/specs/**/*.spec.ts'], maxInstances: 1, // Tauri service configuration services: [['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app.exe', // Adjust for your OS/app name driverProvider: 'embedded', // Use embedded WebDriver (recommended, no external drivers needed) // driverProvider: 'official', // Use external tauri-driver (explicit opt-in) // driverProvider: 'crabnebula', // Use CrabNebula (requires paid API key) }]], // Capabilities capabilities: [{ browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe', // Path to built binary }, }], // Logging logLevel: 'info', bail: 0, baseUrl: 'http://localhost:4444', waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, // Test configuration framework: 'mocha', mochaOpts: { ui: 'bdd', timeout: 60000, }, }; ``` ### 3. Create a Test[​](#3-create-a-test "Direct link to 3. Create a Test") Create `test/specs/example.spec.ts`: ``` describe('My Tauri App', () => { it('should display hello world', async () => { // Wait for the app to fully load await browser.pause(500); // Find and check a heading const heading = await browser.$('h1'); expect(await heading.getText()).toBe('Hello, Tauri!'); }); it('should execute Tauri commands', async () => { // Execute JavaScript in the Tauri frontend context with access to Tauri APIs const result = await browser.tauri.execute(({ core }) => { return core.invoke('get_platform_info'); }); console.log('Platform info:', result); }); it('should mock Tauri commands', async () => { // Mock a Tauri command const mock = await browser.tauri.mock('get_user'); await mock.mockReturnValue({ id: 1, name: 'Test User' }); // Execute code that uses the mocked command const user = await browser.tauri.execute(({ core }) => { return core.invoke('get_user'); }); expect(user).toEqual({ id: 1, name: 'Test User' }); }); }); ``` ## Running Tests[​](#running-tests "Direct link to Running Tests") ### Run All Tests[​](#run-all-tests "Direct link to Run All Tests") ``` npx wdio run wdio.conf.ts ``` ### Run Specific Test File[​](#run-specific-test-file "Direct link to Run Specific Test File") ``` npx wdio run wdio.conf.ts --spec test/specs/example.spec.ts ``` ### Run in Watch Mode[​](#run-in-watch-mode "Direct link to Run in Watch Mode") ``` npx wdio run wdio.conf.ts --watch ``` ### Run with Debug Logging[​](#run-with-debug-logging "Direct link to Run with Debug Logging") ``` npx wdio run wdio.conf.ts --logLevel debug ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### "Cannot find module '@wdio/tauri-plugin'"[​](#cannot-find-module-wdiotauri-plugin "Direct link to \"Cannot find module '@wdio/tauri-plugin'\"") The frontend plugin import is failing. Make sure: 1. Install the peer dependencies: ``` npm install --save-dev @wdio/tauri-plugin ``` 2. The import is in your HTML/JS entry point before tests run ### "tauri-driver not found" or "No driverProvider configured"[​](#tauri-driver-not-found-or-no-driverprovider-configured "Direct link to \"tauri-driver not found\" or \"No driverProvider configured\"") The service couldn't determine which driver to use, or couldn't find tauri-driver. Solutions: 1. **Use embedded provider** (no external driver needed): ``` driverProvider: 'embedded' ``` Requires `tauri-plugin-wdio-webdriver` in your Tauri app. On macOS this is auto-detected. 2. **Install tauri-driver manually** (if using `driverProvider: 'official'`): ``` cargo install tauri-driver ``` 3. **Or enable auto-install** in `wdio.conf.ts`: ``` driverProvider: 'official', autoInstallTauriDriver: true ``` ### "Application not found at path"[​](#application-not-found-at-path "Direct link to \"Application not found at path\"") The `appBinaryPath` is wrong. Verify: 1. You built the app in release mode: `cargo build --release` 2. The path exists: `./src-tauri/target/release/my-app.exe` 3. Update the path in `wdio.conf.ts` if needed ### Tests timeout on Windows[​](#tests-timeout-on-windows "Direct link to Tests timeout on Windows") Edge WebDriver version mismatch. The service auto-manages this, but if issues persist: 1. See [Edge WebDriver (Windows)](/docs/desktop-testing/tauri/edge-webdriver-windows.md) 2. Check your Edge version: Settings → About Microsoft Edge 3. Verify the driver version matches ### "Test failed with Firefox" Error[​](#test-failed-with-firefox-error "Direct link to \"Test failed with Firefox\" Error") Make sure you're using `browserName: 'tauri'` in capabilities, not other browsers. ## Next Steps[​](#next-steps "Direct link to Next Steps") 1. **Add more tests** - See [Usage Examples](/docs/desktop-testing/tauri/usage-examples.md) for patterns 2. **Advanced features** - Read about [Mocking](/docs/desktop-testing/tauri/api.md#mock-functions) and [Logging](/docs/desktop-testing/tauri/log-forwarding.md) 3. **Configure the service** - See [Configuration](/docs/desktop-testing/tauri/configuration.md) for all options 4. **Debug issues** - Check [Troubleshooting](/docs/desktop-testing/tauri/troubleshooting.md) ## Common Patterns[​](#common-patterns "Direct link to Common Patterns") ### Test Custom Tauri Commands[​](#test-custom-tauri-commands "Direct link to Test Custom Tauri Commands") ``` it('should call custom commands', async () => { const result = await browser.tauri.execute(({ core }) => { return core.invoke('my_custom_command', { param: 'value' }); }); expect(result).toBeDefined(); }); ``` ### Capture Logs[​](#capture-logs "Direct link to Capture Logs") Enable log capture in `wdio.conf.ts`: ``` services: [['@wdio/tauri-service', { captureBackendLogs: true, captureFrontendLogs: true, backendLogLevel: 'debug', frontendLogLevel: 'debug', }]], ``` ### Multiremote Testing[​](#multiremote-testing "Direct link to Multiremote Testing") Run multiple instances of your app: ``` capabilities: [ { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe', }, }, { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe', }, }, ], ``` ### CI/CD Integration[​](#cicd-integration "Direct link to CI/CD Integration") Example GitHub Actions workflow: ``` name: E2E Tests on: [push, pull_request] jobs: test: runs-on: windows-latest # or ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - uses: dtolnay/rust-toolchain@stable - name: Install dependencies run: npm install - name: Build Tauri app run: npm run tauri build - name: Run tests run: npm run test:e2e ``` ## See Also[​](#see-also "Direct link to See Also") * [Configuration Reference](/docs/desktop-testing/tauri/configuration.md) * [API Reference](/docs/desktop-testing/tauri/api.md) * [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) * [Platform Support](/docs/desktop-testing/tauri/platform-support.md) * [Troubleshooting](/docs/desktop-testing/tauri/troubleshooting.md) * [WebdriverIO Documentation](https://webdriver.io/docs) * [Tauri Documentation](https://v2.tauri.app) --- Source: https://webdriver.io/docs/desktop-testing/tauri/configuration.md # Configuration Complete guide to configuring @wdio/tauri-service in your WebdriverIO setup. ## Service Configuration[​](#service-configuration "Direct link to Service Configuration") Add the Tauri service to your `wdio.conf.ts`: ``` export const config = { services: [ ['@wdio/tauri-service', { // Service options go here autoInstallTauriDriver: true, autoDownloadEdgeDriver: true, captureBackendLogs: true, captureFrontendLogs: true, }] ], // ... rest of config }; ``` ## Service Options[​](#service-options "Direct link to Service Options") ### `appBinaryPath`[​](#appbinarypath "Direct link to appbinarypath") * Type `string` * Default `Auto-detected from capabilities if not provided` * Required `No` Path to the compiled Tauri application binary (executable). **Example:** ``` appBinaryPath: './src-tauri/target/release/my-app.exe', // Windows appBinaryPath: './src-tauri/target/release/my-app', // Linux ``` **Note:** Path should be absolute or relative to the WebdriverIO config directory. ### `appArgs`[​](#appargs "Direct link to appargs") * Type `string[]` * Default `[]` * Required `No` Command-line arguments to pass to the Tauri application when launching. Each array element is passed as a separate argument — no shell parsing is applied. **Example:** ``` appArgs: ['--debug', '--log-level', 'debug'] // For key=value style arguments, use either form: appArgs: ['--window-size', '1920,1080'] // Two separate elements appArgs: ['--window-size=1920,1080'] // Single element with equals ``` ### `autoInstallTauriDriver`[​](#autoinstalltauridriver "Direct link to autoinstalltauridriver") * Type `boolean` * Default `false` * Required `No` Automatically install `tauri-driver` if not found in PATH. **Requirements:** * Rust toolchain must be installed (`cargo`) * First installation will take a few minutes **Example:** ``` autoInstallTauriDriver: true ``` **Note:** Disable if you have `tauri-driver` installed manually or globally. ### `autoDownloadEdgeDriver`[​](#autodownloadedgedriver "Direct link to autodownloadedgedriver") * Type `boolean` * Default `true` * Required `No` Automatically download MSEdgeDriver on Windows if version mismatch detected. **Example:** ``` autoDownloadEdgeDriver: true // Windows only ``` **Note:** Windows only, ignored on Linux/macOS. See [Edge WebDriver Windows](/docs/desktop-testing/tauri/edge-webdriver-windows.md). ### `tauriDriverPort`[​](#tauridriverport "Direct link to tauridriverport") * Type `number` * Default `4444` * Required `No` Port for tauri-driver to listen on. Each worker process gets a unique port (port + worker index). **Example:** ``` tauriDriverPort: 4444 ``` **Note:** Increment for multiremote to avoid port conflicts. ### `tauriDriverPath`[​](#tauridriverpath "Direct link to tauridriverpath") * Type `string` * Default `Use tauri-driver from PATH` * Required `No` Path to the `tauri-driver` executable if not in PATH. **Example:** ``` tauriDriverPath: '/usr/local/bin/tauri-driver' // Linux/macOS tauriDriverPath: 'C:\\tools\\tauri-driver.exe' // Windows ``` ### `logLevel`[​](#loglevel "Direct link to loglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` * Required `No` Log level for tauri-driver output. **Example:** ``` logLevel: 'debug' // More verbose ``` ### `windowLabel`[​](#windowlabel "Direct link to windowlabel") * Type `string` * Default `'main'` * Required `No` The default window label to target for Tauri operations. This controls which webview window `browser.tauri.execute()` and other Tauri-specific operations target by default. **Example:** ``` windowLabel: 'settings' // Target the settings window by default ``` **Note:** * Each browser instance (including multiremote) can have its own default windowLabel * Override at runtime with `browser.tauri.switchWindow(label)` * Per-call override with `browser.tauri.execute(fn, withExecuteOptions({ windowLabel: 'x' }))` is supported ### `commandTimeout`[​](#commandtimeout "Direct link to commandtimeout") * Type `number` * Default `30000 (30 seconds)` * Required `No` Timeout in milliseconds for individual command execution. **Example:** ``` commandTimeout: 60000 // 60 seconds ``` ### `startTimeout`[​](#starttimeout "Direct link to starttimeout") * Type `number` * Default `30000 for the 'official' and 'crabnebula' providers, 60000 for the 'embedded' provider (the embedded WebDriver server takes longer to come up, especially on Windows CI).` * Required `No` Timeout in milliseconds for the Tauri app to start and become ready. **Example:** ``` startTimeout: 60000 // 60 seconds ``` ### `captureBackendLogs`[​](#capturebackendlogs "Direct link to capturebackendlogs") * Type `boolean` * Default `false` * Required `No` Capture logs from the Tauri backend (Rust code). **Example:** ``` captureBackendLogs: true ``` **Note:** When enabled, logs appear in WebdriverIO reports. See [Log Forwarding](/docs/desktop-testing/tauri/log-forwarding.md). ### `captureFrontendLogs`[​](#capturefrontendlogs "Direct link to capturefrontendlogs") * Type `boolean` * Default `false` * Required `No` Capture console logs from the frontend (JavaScript/TypeScript). **Example:** ``` captureFrontendLogs: true ``` **Note:** When enabled, console.log() calls appear in WebdriverIO reports. See [Log Forwarding](/docs/desktop-testing/tauri/log-forwarding.md). ### `backendLogLevel`[​](#backendloglevel "Direct link to backendloglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` * Required `No` Minimum log level to capture from backend. Logs below this level are ignored. **Example:** ``` backendLogLevel: 'debug' // Capture debug and above ``` **Note:** Only has effect if `captureBackendLogs: true`. ### `frontendLogLevel`[​](#frontendloglevel "Direct link to frontendloglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` * Required `No` Minimum log level to capture from frontend. Logs below this level are ignored. **Example:** ``` frontendLogLevel: 'debug' ``` **Note:** Only has effect if `captureFrontendLogs: true`. ### `logDir`[​](#logdir "Direct link to logdir") * Type `string` * Default `Logs to stdout/stderr` * Required `No` Directory to store logs from the Tauri service (for standalone mode). **Example:** ``` logDir: './test-logs' ``` ### `statusPollTimeout`[​](#statuspolltimeout "Direct link to statuspolltimeout") * Type `number` * Default `2000` * Required `No` Timeout in milliseconds for the `/status` endpoint poll during embedded WebDriver server startup. Increase this in slow CI environments (e.g. containerised Windows runners) where a healthy-but-busy server may miss the default deadline and trigger a false-positive restart. **Example:** ``` statusPollTimeout: 5000 ``` **Note:** Only applies when `driverProvider: 'embedded'`. ### `clearMocks`[​](#clearmocks "Direct link to clearmocks") * Type `boolean` * Default `false` * Required `No` If `true`, all mock call history is cleared before each test. Equivalent to calling `browser.tauri.clearAllMocks()` in a `beforeEach`. **Example:** ``` clearMocks: true ``` ### `clearMocksPrefix`[​](#clearmocksprefix "Direct link to clearmocksprefix") * Type `string` * Default `undefined` * Required `No` If set, only mocks whose command name starts with this prefix are cleared. Only used when `clearMocks: true`. **Example:** ``` clearMocks: true, clearMocksPrefix: 'clipboard' // Only clears clipboard.* mocks ``` ### `resetMocks`[​](#resetmocks "Direct link to resetmocks") * Type `boolean` * Default `false` * Required `No` If `true`, all mocks are reset (implementation + history) before each test. Equivalent to `browser.tauri.resetAllMocks()` in a `beforeEach`. **Example:** ``` resetMocks: true ``` ### `resetMocksPrefix`[​](#resetmocksprefix "Direct link to resetmocksprefix") * Type `string` * Default `undefined` * Required `No` If set, only mocks whose command name starts with this prefix are reset. Only used when `resetMocks: true`. ### `restoreMocks`[​](#restoremocks "Direct link to restoremocks") * Type `boolean` * Default `false` * Required `No` If `true`, all mocks are restored to their original implementations before each test. Equivalent to `browser.tauri.restoreAllMocks()` in a `beforeEach`. **Example:** ``` restoreMocks: true ``` ### `restoreMocksPrefix`[​](#restoremocksprefix "Direct link to restoremocksprefix") * Type `string` * Default `undefined` * Required `No` If set, only mocks whose command name starts with this prefix are restored. Only used when `restoreMocks: true`. ### `driverProvider`[​](#driverprovider "Direct link to driverprovider") * Type `'official' | 'crabnebula' | 'embedded'` * Default `Auto-detected (see above). Set explicitly to override.` * Required `No` Select which driver provider to use for WebDriver communication. * `'embedded'`: Use embedded WebDriver server via tauri-plugin-wdio-webdriver (no external driver needed, works on all platforms) * `'official'`: Use the cargo-installed tauri-driver (supports Windows/Linux) * `'crabnebula'`: Use @crabnebula/tauri-driver from npm (supports Windows/Linux/macOS; CN\_API\_KEY required for macOS only) **Auto-detection (no explicit config needed):** The service automatically selects `'embedded'` when either of the following signals is present: * `TAURI_WEBDRIVER_PORT` environment variable is set (you've configured the plugin's port) * Running on macOS (WKWebView requires the embedded approach) If neither signal is present on Windows or Linux, the service throws an immediate error with instructions. **Example:** ``` // Auto-detected on macOS, or when TAURI_WEBDRIVER_PORT is set — no config needed // driverProvider: 'embedded' (set this explicitly to be unambiguous) // Use CrabNebula — all platforms; CN_API_KEY required for macOS driverProvider: 'crabnebula' // Use official tauri-driver — opt out of embedded provider driverProvider: 'official' ``` **Note:** Install `tauri-plugin-wdio-webdriver` in your Tauri app to use the embedded provider. See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) for details. ### Choosing a Driver Provider[​](#choosing-a-driver-provider "Direct link to Choosing a Driver Provider") | Provider | Platform Support | External driver required | Notes | | -------------- | --------------------- | --------------------------------------------- | ---------------------------------------------------------------------- | | `'embedded'` | Windows, Linux, macOS | No | No external deps; auto-detected on macOS or via `TAURI_WEBDRIVER_PORT` | | `'official'` | Windows, Linux | Yes (tauri-driver + platform driver) | Explicit opt-in; cargo-installed | | `'crabnebula'` | Windows, Linux, macOS | Yes (platform driver; CN\_API\_KEY for macOS) | Fork of official driver; good fit if already on CrabNebula platform | **Recommendation:** * **`'embedded'`** — simplest setup: no external driver installation, works on all three platforms * **`'crabnebula'`** — best if you are already using CrabNebula Cloud or want a single driver config across all platforms; macOS testing requires a CrabNebula subscription * **`'official'`** — explicit opt-in for Windows/Linux if you have `tauri-driver` already installed ### `embeddedPort`[​](#embeddedport "Direct link to embeddedport") * Type `number` * Default `4445` * Required `No` Port for the embedded WebDriver server. Only used when `driverProvider: 'embedded'`. * The service spawns your Tauri app with this port * Each worker instance gets a unique port (basePort + workerIndex) * Can also be set via the `TAURI_WEBDRIVER_PORT` or `WDIO_EMBEDDED_PORT` environment variable. Setting either env var also serves as the auto-detection signal that opts you into the embedded provider on Windows/Linux. **Example:** ``` embeddedPort: 4445 ``` **Note:** Port must be available. The service will fail if the port is in use. ### `crabnebulaDriverPath`[​](#crabnebuladriverpath "Direct link to crabnebuladriverpath") * Type `string` * Default `Auto-detected from node_modules` * Required `No` Path to the @crabnebula/tauri-driver executable. Only used when `driverProvider: 'crabnebula'`. **Example:** ``` crabnebulaDriverPath: './node_modules/.bin/tauri-driver' ``` ### `crabnebulaManageBackend`[​](#crabnebulamanagebackend "Direct link to crabnebulamanagebackend") * Type `boolean` * Default `true when using CrabNebula on macOS` * Required `No` Auto-manage the test-runner-backend process (macOS only). When enabled, the service will automatically start and stop the backend. **Example:** ``` crabnebulaManageBackend: true ``` ### `crabnebulaBackendPort`[​](#crabnebulabackendport "Direct link to crabnebulabackendport") * Type `number` * Default `3000` * Required `No` Port for the test-runner-backend to listen on (macOS only). **Example:** ``` crabnebulaBackendPort: 3000 ``` ## Capabilities Configuration[​](#capabilities-configuration "Direct link to Capabilities Configuration") Configure Tauri-specific capabilities in your `capabilities` array: ### Basic Configuration[​](#basic-configuration "Direct link to Basic Configuration") ``` capabilities: [{ browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe' } }] ``` > `browserName` accepts either `'tauri'` (preferred) or `'wry'` (the underlying webview library). Both are treated identically by the service. ### Full Configuration[​](#full-configuration "Direct link to Full Configuration") ``` capabilities: [{ browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe', args: ['--debug'] }, // Optional: override service settings per capability // tauriDriverPort: 4445, }] ``` ### Multiremote Configuration[​](#multiremote-configuration "Direct link to Multiremote Configuration") Run multiple instances of the app: ``` capabilities: { app1: { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe' } }, app2: { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe' } } } ``` Or as array: ``` capabilities: [ { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe' } }, { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe' } } ] ``` ## Complete Configuration Example[​](#complete-configuration-example "Direct link to Complete Configuration Example") ``` // wdio.conf.ts export const config = { runner: 'local', // Specs specs: ['./test/specs/**/*.spec.ts'], exclude: ['./test/specs/integration/**/*.spec.ts'], // Parallelization maxInstances: 1, maxInstancesPerCapability: 1, // Tauri Service services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app.exe', appArgs: ['--debug'], autoInstallTauriDriver: true, autoDownloadEdgeDriver: true, // Windows only tauriDriverPort: 4444, logLevel: 'info', commandTimeout: 30000, startTimeout: 30000, captureBackendLogs: true, captureFrontendLogs: true, backendLogLevel: 'debug', frontendLogLevel: 'debug', }] ], // Capabilities capabilities: [{ browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/release/my-app.exe', args: ['--debug'] } }], // Connection settings logLevel: 'info', bail: 0, baseUrl: 'http://localhost:4444', waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, // Framework framework: 'mocha', mochaOpts: { ui: 'bdd', timeout: 60000 }, // Reporters reporters: ['spec'], // Hooks onPrepare: async (config, capabilities) => { console.log('Starting test run...'); }, onComplete: async (exitCode, config, capabilities, results) => { console.log('Test run completed'); } }; ``` ## Platform-Specific Configuration[​](#platform-specific-configuration "Direct link to Platform-Specific Configuration") ### Windows Configuration[​](#windows-configuration "Direct link to Windows Configuration") Enable auto Edge WebDriver management: ``` services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app.exe', autoDownloadEdgeDriver: true, // Auto-download on version mismatch }] ] ``` ### Linux Configuration[​](#linux-configuration "Direct link to Linux Configuration") WebKitWebDriver is auto-detected: ``` services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app', autoInstallTauriDriver: true, }] ] ``` ### Headless Configuration (Linux)[​](#headless-configuration-linux "Direct link to Headless Configuration (Linux)") Run tests without a display server: ``` services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app', // Xvfb is auto-detected if available (WebdriverIO 9.19.1+) }] ] ``` ## Finding Your appBinaryPath[​](#finding-your-appbinarypath "Direct link to Finding Your appBinaryPath") ### Windows[​](#windows "Direct link to Windows") Build your app: ``` cd src-tauri cargo build --release ``` Binary is at: ``` ./src-tauri/target/release/my-app.exe ``` (Replace `my-app` with your app name from `Cargo.toml`) ### Linux[​](#linux "Direct link to Linux") Build your app: ``` cd src-tauri cargo build --release ``` Binary is at: ``` ./src-tauri/target/release/my-app ``` (Replace `my-app` with your app name) ### Verify Binary Exists[​](#verify-binary-exists "Direct link to Verify Binary Exists") ``` # Windows if exist "src-tauri\target\release\my-app.exe" echo "Binary found" # Linux/macOS ls -la src-tauri/target/release/my-app ``` ## Configuration Validation[​](#configuration-validation "Direct link to Configuration Validation") Check your configuration with: ``` # Verify service can be loaded npx wdio config # Run with verbose logging npx wdio run wdio.conf.ts --logLevel debug ``` ## Common Configuration Patterns[​](#common-configuration-patterns "Direct link to Common Configuration Patterns") ### Development Configuration[​](#development-configuration "Direct link to Development Configuration") ``` export const config = { // ... other settings services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app.exe', autoInstallTauriDriver: true, autoDownloadEdgeDriver: true, captureBackendLogs: true, captureFrontendLogs: true, backendLogLevel: 'debug', frontendLogLevel: 'debug', logLevel: 'debug', }] ], }; ``` ### CI/CD Configuration[​](#cicd-configuration "Direct link to CI/CD Configuration") ``` export const config = { // ... other settings services: [ ['@wdio/tauri-service', { appBinaryPath: process.env.APP_BINARY || './src-tauri/target/release/my-app.exe', autoInstallTauriDriver: true, autoDownloadEdgeDriver: true, captureBackendLogs: true, captureFrontendLogs: true, logLevel: 'info', }] ], }; ``` ### Production-Like Configuration[​](#production-like-configuration "Direct link to Production-Like Configuration") ``` export const config = { // ... other settings services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app.exe', autoInstallTauriDriver: false, // Pre-installed autoDownloadEdgeDriver: false, // Pre-downloaded captureBackendLogs: false, captureFrontendLogs: false, logLevel: 'warn', }] ], }; ``` ## Troubleshooting Configuration Issues[​](#troubleshooting-configuration-issues "Direct link to Troubleshooting Configuration Issues") **"Cannot find appBinaryPath"** 1. Verify path exists: ``` ls -la src-tauri/target/release/my-app* ``` 2. Build the app first: ``` cd src-tauri && cargo build --release ``` 3. Use absolute path in config: ``` appBinaryPath: path.resolve('./src-tauri/target/release/my-app.exe') ``` **"Service not found"** Ensure service is installed: ``` npm list @wdio/tauri-service ``` If missing: ``` npm install --save-dev @wdio/tauri-service ``` **"Port already in use"** Change the tauri-driver port: ``` tauriDriverPort: 4445 // Instead of 4444 ``` Or enable multiremote with auto-port assignment: ``` maxInstances: 3 // Each gets unique port ``` ## See Also[​](#see-also "Direct link to See Also") * [Quick Start](/docs/desktop-testing/tauri/quick-start.md) for getting started * [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) for Tauri plugin configuration * [API Reference](/docs/desktop-testing/tauri/api.md) for available functions * [Log Forwarding](/docs/desktop-testing/tauri/log-forwarding.md) for logging configuration --- Source: https://webdriver.io/docs/desktop-testing/tauri/api.md # API Reference Complete API reference for @wdio/tauri-service. ## browser.tauri API[​](#browsertauri-api "Direct link to browser.tauri API") The following methods are available on the `browser.tauri` object when connected to a Tauri app. ### `browser.tauri.execute(script, ...args)`[​](#browsertauriexecutescript-args "Direct link to browsertauriexecutescript-args") Execute JavaScript code in the Tauri frontend context with access to Tauri APIs. Requires tauri-plugin-wdio to be installed and configured. **Parameters:** * `script` (Function | string) - JavaScript code to execute. If a function, receives Tauri APIs as the first parameter * `...args` (any\[]) - Additional arguments passed to the script **Returns:** `Promise\` **Example:** ``` // Execute with destructured Tauri APIs const result = await browser.tauri.execute(({ core }) => { return core.invoke('get_platform_info'); }); // Execute with full Tauri APIs object const version = await browser.tauri.execute(async (tauri) => { return tauri.app?.getVersion(); }); // Execute with arguments const result = await browser.tauri.execute( (tauri, name) => tauri.core.invoke('greet', { name }), 'World' ); // Execute string of code const result = await browser.tauri.execute('window.location.href'); ``` **Note:** Requires tauri-plugin-wdio to be installed. See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md). ### `browser.tauri.mock(command)`[​](#browsertaurimockcommand "Direct link to browsertaurimockcommand") Mock a specific Tauri backend command. Returns a TauriMock object for configuring the mock behavior. **Parameters:** * `command` (string) - Name of the Tauri command to mock **Returns:** `Promise\` **Example:** ``` const mock = await browser.tauri.mock('read_file'); await mock.mockReturnValue('mocked file content'); // Now calling invoke('read_file', ...) returns 'mocked file content' const content = await browser.tauri.execute(({ core }) => core.invoke('read_file')); expect(content).toBe('mocked file content'); ``` ### `browser.tauri.isMockFunction(fn)`[​](#browsertauriismockfunctionfn "Direct link to browsertauriismockfunctionfn") Check if a value is a Tauri mock function. This is a TypeScript type guard. **Parameters:** * `fn` (unknown) - Value to check **Returns:** `boolean` (type narrows to `TauriMockInstance` when true) **Example:** ``` const mock = await browser.tauri.mock('clipboard_read'); if (browser.tauri.isMockFunction(mock)) { // TypeScript knows mock is TauriMockInstance here expect(mock.mock.calls).toHaveLength(1); } ``` ### `browser.tauri.clearAllMocks(commandPrefix?)`[​](#browsertauriclearallmockscommandprefix "Direct link to browsertauriclearallmockscommandprefix") Clear all mock call history and reset results, but keep the mock implementations in place. **Parameters:** * `commandPrefix` (string, optional) - If provided, only mocks with command names starting with this prefix will be cleared **Returns:** `Promise` **Example:** ``` // Clear all mocks await browser.tauri.clearAllMocks(); // Clear only clipboard-related mocks await browser.tauri.clearAllMocks('clipboard'); ``` ### `browser.tauri.resetAllMocks(commandPrefix?)`[​](#browsertauriresetallmockscommandprefix "Direct link to browsertauriresetallmockscommandprefix") Reset all mocks to their initial state (clears implementations and call history). **Parameters:** * `commandPrefix` (string, optional) - If provided, only mocks with matching prefix are reset **Returns:** `Promise` ### `browser.tauri.restoreAllMocks(commandPrefix?)`[​](#browsertaurirestoreallmockscommandprefix "Direct link to browsertaurirestoreallmockscommandprefix") Remove all mocks and restore original command implementations. **Parameters:** * `commandPrefix` (string, optional) - If provided, only mocks with matching prefix are restored **Returns:** `Promise` **Example:** ``` await browser.tauri.restoreAllMocks(); // Commands now call the real Tauri backend again ``` ### `browser.tauri.triggerDeeplink(url)`[​](#browsertauritriggerdeeplinkurl "Direct link to browsertauritriggerdeeplinkurl") Trigger a deeplink to the Tauri application for testing protocol handlers. Uses platform-specific commands (`open` on macOS, `xdg-open` on Linux, `cmd /c start` on Windows). **Parameters:** * `url` (string) - The deeplink URL to trigger (e.g., `'myapp://open?file=test.txt'`) **Returns:** `Promise` **Example:** ``` await browser.tauri.triggerDeeplink('myapp://open?file=test.txt'); await browser.waitUntil(async () => { const openedFile = await browser.tauri.execute(() => { return globalThis.lastOpenedFile; }); return openedFile === 'test.txt'; }); ``` See [Deeplink Testing](/docs/desktop-testing/tauri/deeplink-testing.md) for full usage guide. ### `browser.tauri.switchWindow(label)`[​](#browsertauriswitchwindowlabel "Direct link to browsertauriswitchwindowlabel") Switch the active Tauri window for subsequent operations. Changes the window that `browser.tauri.execute()` and other Tauri-specific operations target. **Parameters:** * `label` (string) - The window label to switch to (e.g., `'main'`, `'settings'`) **Returns:** `Promise` **Example:** ``` // Switch to the settings window await browser.tauri.switchWindow('settings'); // Now executes in the settings window context const data = await browser.tauri.execute(({ core }) => core.invoke('get_settings')); // Switch back to main window await browser.tauri.switchWindow('main'); ``` **Note:** The window label must exist in your Tauri app. Use `browser.tauri.listWindows()` to get available labels. ### `browser.tauri.listWindows()`[​](#browsertaurilistwindows "Direct link to browsertaurilistwindows") Get a list of all available Tauri window labels in the application. **Returns:** `Promise` **Example:** ``` const windows = await browser.tauri.listWindows(); console.log(windows); // ['main', 'settings', 'dialog'] ``` ## Updating browser.tauri.execute with Per-Call Options[​](#updating-browsertauriexecute-with-per-call-options "Direct link to Updating browser.tauri.execute with Per-Call Options") The `execute` method supports optional per-call options to override session defaults: **Parameters:** * `script` (Function | string) - JavaScript code to execute * `options` (object, optional) - Per-call execution options * `windowLabel` (string) - Override the default window for this call only * `...args` (any\[]) - Additional arguments passed to the script **Example:** ``` import { withExecuteOptions } from '@wdio/tauri-service'; // Execute in a specific window without changing session default const result = await browser.tauri.execute( (tauri) => tauri.core.invoke('get_data'), withExecuteOptions({ windowLabel: 'popup' }) ); // Can also pass arguments after options const greeting = await browser.tauri.execute( (tauri, name) => tauri.core.invoke('greet', { name }), withExecuteOptions({ windowLabel: 'settings' }), 'Alice' ); ``` ## TauriMock Interface[​](#taurimock-interface "Direct link to TauriMock Interface") When you call `browser.tauri.mock(command)`, you receive a TauriMock object with these methods: ### `mockImplementation(fn)`[​](#mockimplementationfn "Direct link to mockimplementationfn") Set a custom implementation function for the mock. **Returns:** `Promise\` **Example:** ``` const mock = await browser.tauri.mock('calculate'); await mock.mockImplementation(async (args) => args.x + args.y); const result = await browser.tauri.execute(({ core }) => core.invoke('calculate', { x: 5, y: 3 })); // result === 8 ``` ### `mockImplementationOnce(fn)`[​](#mockimplementationoncefn "Direct link to mockimplementationoncefn") Set a custom implementation for the next call only. **Returns:** `Promise\` ### `mockReturnValue(value)`[​](#mockreturnvaluevalue "Direct link to mockreturnvaluevalue") Set the mock to always return a specific value. **Returns:** `Promise\` **Example:** ``` const mock = await browser.tauri.mock('get_user'); await mock.mockReturnValue({ id: 1, name: 'John' }); ``` ### `mockReturnValueOnce(value)`[​](#mockreturnvalueoncevalue "Direct link to mockreturnvalueoncevalue") Set the mock to return a specific value for the next call only. **Returns:** `Promise\` **Example:** ``` const mock = await browser.tauri.mock('counter'); await mock.mockReturnValueOnce(1); await mock.mockReturnValueOnce(2); await mock.mockReturnValue(3); // default for subsequent calls ``` ### `mockResolvedValue(value)`[​](#mockresolvedvaluevalue "Direct link to mockresolvedvaluevalue") Set the mock to return a promise that resolves to the given value. **Returns:** `Promise\` ### `mockResolvedValueOnce(value)`[​](#mockresolvedvalueoncevalue "Direct link to mockresolvedvalueoncevalue") Set the mock to resolve to a value for the next call only. **Returns:** `Promise\` ### `mockRejectedValue(error)`[​](#mockrejectedvalueerror "Direct link to mockrejectedvalueerror") Set the mock to return a promise that rejects with an error. **Returns:** `Promise\` **Example:** ``` const mock = await browser.tauri.mock('risky_operation'); await mock.mockRejectedValue(new Error('Operation failed')); ``` ### `mockRejectedValueOnce(error)`[​](#mockrejectedvalueonceerror "Direct link to mockrejectedvalueonceerror") Set the mock to reject for the next call only. **Returns:** `Promise\` ### `mockClear()`[​](#mockclear "Direct link to mockclear") Clear the call history of this mock without resetting its implementation. **Returns:** `Promise\` ### `mockReset()`[​](#mockreset "Direct link to mockreset") Reset the mock to its initial state (clears both implementation and call history). **Returns:** `Promise\` ### `mockRestore()`[​](#mockrestore "Direct link to mockrestore") Remove this mock and restore the original command implementation. **Returns:** `Promise\` ### `mockReturnThis()`[​](#mockreturnthis "Direct link to mockreturnthis") Set the mock to return `this` when called (useful for chaining). **Returns:** `Promise\` ### `mockName(name)` / `getMockName()`[​](#mocknamename--getmockname "Direct link to mocknamename--getmockname") Set or get a display name for the mock (useful for debugging). ### `getMockImplementation()`[​](#getmockimplementation "Direct link to getmockimplementation") Get the current implementation function of the mock. ### `update()`[​](#update "Direct link to update") Sync mock call data from the inner mock (app context) to the outer mock (test process). **Returns:** `Promise\` ### `withImplementation(implFn, callbackFn)`[​](#withimplementationimplfn-callbackfn "Direct link to withimplementationimplfn-callbackfn") Temporarily use a different implementation for the duration of a callback. **Example:** ``` const mock = await browser.tauri.mock('my_command'); await mock.mockReturnValue('default'); await mock.withImplementation( () => 'temporary', async () => { const result = await browser.tauri.execute(({ core }) => core.invoke('my_command')); console.log(result); // 'temporary' } ); const result = await browser.tauri.execute(({ core }) => core.invoke('my_command')); console.log(result); // 'default' ``` ### Mock Properties[​](#mock-properties "Direct link to Mock Properties") * `mock.calls` - Array of call arguments * `mock.results` - Array of call results * `__isTauriMock` - Boolean flag identifying Tauri mocks ## Package Exports[​](#package-exports "Direct link to Package Exports") These functions are exported from `@wdio/tauri-service` for use in standalone mode or custom setups. ### `getTauriAppInfo(appPath)`[​](#gettauriappinfoapppath "Direct link to gettauriappinfoapppath") Get information about a Tauri application from its tauri.conf.json. **Parameters:** * `appPath` (string) - Path to the Tauri app directory **Returns:** `Promise\` **Example:** ``` import { getTauriAppInfo } from '@wdio/tauri-service'; const appInfo = await getTauriAppInfo('./fixtures/e2e-apps/tauri'); console.log(appInfo.name); // e.g., "my-app" console.log(appInfo.version); // e.g., "0.1.0" console.log(appInfo.binaryPath); // resolved path to binary console.log(appInfo.configPath); // path to tauri.conf.json console.log(appInfo.targetDir); // path to target directory ``` ### `getTauriBinaryPath(appPath)`[​](#gettauribinarypathapppath "Direct link to gettauribinarypathapppath") Resolve the path to the Tauri application binary. Handles platform-specific paths (`.exe` on Windows, `.app` on macOS, etc.). **Parameters:** * `appPath` (string) - Path to the Tauri app directory **Returns:** `Promise` **Example:** ``` import { getTauriBinaryPath } from '@wdio/tauri-service'; const binaryPath = await getTauriBinaryPath('./fixtures/e2e-apps/tauri'); ``` ### `startWdioSession(capabilities, globalOptions?)`[​](#startwdiosessioncapabilities-globaloptions "Direct link to startwdiosessioncapabilities-globaloptions") Initialize the Tauri service in standalone mode. Use this when you want to manage the session manually outside of WebdriverIO's lifecycle. **Parameters:** * `capabilities` (Capabilities) - WebdriverIO capabilities with Tauri options * `globalOptions?` (TauriServiceGlobalOptions) - Global service options **Returns:** `Promise\` **Example:** ``` import { startWdioSession } from '@wdio/tauri-service'; const browser = await startWdioSession({ browserName: 'tauri', 'tauri:options': { application: './path/to/app.exe' } }); // Use browser... await browser.deleteSession(); ``` ### `cleanupWdioSession(browser)`[​](#cleanupwdiosessionbrowser "Direct link to cleanupwdiosessionbrowser") Clean up a Tauri session started with `startWdioSession`. **Parameters:** * `browser` (WebdriverIO.Browser) - Browser instance to clean up **Returns:** `Promise` ### `createTauriCapabilities(appBinaryPath, options?)`[​](#createtauricapabilitiesappbinarypath-options "Direct link to createtauricapabilitiesappbinarypath-options") Create Tauri-specific capabilities for use in WebdriverIO config. **Parameters:** * `appBinaryPath` (string) - Path to the Tauri app binary * `options?` (Partial\) - Optional Tauri service options **Returns:** `TauriCapabilities` **Example:** ``` import { createTauriCapabilities } from '@wdio/tauri-service'; const capabilities = createTauriCapabilities('./path/to/app.exe', { captureBackendLogs: true }); ``` ## Exported Types[​](#exported-types "Direct link to Exported Types") ### `TauriAppInfo`[​](#tauriappinfo "Direct link to tauriappinfo") ``` interface TauriAppInfo { name: string; version: string; binaryPath: string; configPath: string; targetDir: string; } ``` ### `TauriCapabilities`[​](#tauricapabilities "Direct link to tauricapabilities") ``` interface TauriCapabilities extends WebdriverIO.Capabilities { browserName?: 'tauri' | 'wry'; 'tauri:options'?: { application: string; args?: string[]; webviewOptions?: { width?: number; height?: number; }; }; 'wdio:tauriServiceOptions'?: TauriServiceOptions; } ``` ### `TauriServiceOptions`[​](#tauriserviceoptions "Direct link to tauriserviceoptions") ``` interface TauriServiceOptions { appBinaryPath?: string; appArgs?: string[]; tauriDriverPort?: number; tauriDriverPath?: string; logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; commandTimeout?: number; startTimeout?: number; captureBackendLogs?: boolean; captureFrontendLogs?: boolean; backendLogLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; frontendLogLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; driverProvider?: 'official' | 'crabnebula' | 'embedded'; embeddedPort?: number; statusPollTimeout?: number; crabnebulaDriverPath?: string; crabnebulaManageBackend?: boolean; crabnebulaBackendPort?: number; windowLabel?: string; clearMocks?: boolean; clearMocksPrefix?: string; resetMocks?: boolean; resetMocksPrefix?: string; restoreMocks?: boolean; restoreMocksPrefix?: string; env?: Record; autoInstallTauriDriver?: boolean; autoDownloadEdgeDriver?: boolean; logDir?: string; } ``` ### `TauriServiceGlobalOptions`[​](#tauriserviceglobaloptions "Direct link to tauriserviceglobaloptions") Global options passed at the service level (not per-capability). ### `TauriResult`[​](#tauriresultt "Direct link to tauriresultt") Uses the standard Result pattern: ``` type TauriResult = { ok: true; value: T } | { ok: false; error: string }; // Usage if (result.ok) { console.log(result.value); // Success case } else { console.error(result.error); // Error case } ``` ### `TauriCommandContext`[​](#tauricommandcontext "Direct link to tauricommandcontext") ``` interface TauriCommandContext { command: string; args: unknown[]; timeout?: number; } ``` ## Notes[​](#notes "Direct link to Notes") * All `browser.tauri.*` methods require tauri-plugin-wdio to be installed. See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md). * Mocking requires tauri-plugin-wdio for invoke interception to work. * The `triggerDeeplink` method requires the `@tauri-apps/plugin-deep-link` plugin in your app. * For detailed configuration examples, see [Configuration](/docs/desktop-testing/tauri/configuration.md). --- Source: https://webdriver.io/docs/desktop-testing/tauri/plugin-setup.md # Plugin Setup ## Overview[​](#overview "Direct link to Overview") The `tauri-plugin-wdio` is a **required** Tauri plugin that enables WebdriverIO testing of Tauri applications. It provides: * **Execute API** - Run JavaScript code from tests with access to Tauri APIs * **Mocking Support** - Mock Tauri backend commands for isolated testing * **Log Forwarding** - Capture console logs from both frontend and backend * **Invoke Interception** - Enable mocking without backend command modifications ## Two WDIO Plugins[​](#two-wdio-plugins "Direct link to Two WDIO Plugins") There are two Tauri plugins for WebdriverIO testing: | Plugin | Package | Purpose | Required | | ----------------------------- | --------- | ------------------------------------ | -------------------------- | | `tauri-plugin-wdio` | Rust + JS | Execute API, mocking, log forwarding | **Yes** | | `tauri-plugin-wdio-webdriver` | Rust only | Embedded WebDriver server | Only for embedded provider | ### When You Need Each[​](#when-you-need-each "Direct link to When You Need Each") * **`tauri-plugin-wdio`** - Always required for: * Executing JavaScript in the frontend (`browser.tauri.execute()`) * Mocking Tauri commands (`browser.tauri.mock()`) * Capturing frontend and backend logs * **`tauri-plugin-wdio-webdriver`** - Required when using the embedded driver provider: * Provides built-in WebDriver HTTP server * Eliminates need for external tauri-driver * Enables native macOS testing without CrabNebula * Auto-detected on macOS; signal via `TAURI_WEBDRIVER_PORT` on Windows/Linux ## Why Is It Required?[​](#why-is-it-required "Direct link to Why Is It Required?") The `@wdio/tauri-service` explicitly checks for the plugin and will fail if it's not available: ``` Error: Tauri plugin not available. Make sure @wdio/tauri-plugin is installed and registered in your Tauri app. ``` ### What Works Without the Plugin[​](#what-works-without-the-plugin "Direct link to What Works Without the Plugin") Only basic WebDriver operations work without the plugin: * Element interactions (click, type, etc.) * Navigation and page access * Basic WebDriver commands ### What Requires the Plugin[​](#what-requires-the-plugin "Direct link to What Requires the Plugin") All advanced testing features require the plugin: * ✅ `browser.tauri.execute()` - Execute JavaScript with Tauri APIs * ✅ `browser.tauri.mock()` - Mock backend commands * ✅ All mocking operations * ✅ Console log capture * ✅ Backend log forwarding ## Installation Steps[​](#installation-steps "Direct link to Installation Steps") ### Step 1: Add Cargo Dependency[​](#step-1-add-cargo-dependency "Direct link to Step 1: Add Cargo Dependency") Add the plugin to your `src-tauri/Cargo.toml`: ``` [dependencies] tauri = { version = "2", features = ["..your other features.."] } tauri-plugin-wdio = "1" ``` ### Step 2: Register Plugin in Rust[​](#step-2-register-plugin-in-rust "Direct link to Step 2: Register Plugin in Rust") Add the plugin initialization to your `src-tauri/src/main.rs`: ``` fn main() { tauri::Builder::default() .plugin(tauri_plugin_wdio::init()) // Add this line .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` Place it anywhere in the plugin chain - typically after other plugins. ### Step 3: Add Tauri Permissions[​](#step-3-add-tauri-permissions "Direct link to Step 3: Add Tauri Permissions") The plugin requires WDIO permissions in your capabilities. Edit `src-tauri/capabilities/default.json`: ``` { "identifier": "default", "windows": ["main"], "permissions": [ "core:default", "core:window:default", "wdio:default" ] } ``` Or use individual permissions if you prefer fine-grained control: ``` { "permissions": [ "core:default", "core:window:default", "wdio:allow-execute", "wdio:allow-log-frontend", "wdio:allow-debug-plugin", "wdio:allow-get-active-window-label", "wdio:allow-get-window-states", "wdio:allow-list-windows" ] } ``` > **Note:** Mocking is implemented entirely on the JavaScript side via invoke interception (`window.__wdio_mocks__`), so there are no `wdio:allow-set-mock` / `allow-clear-mocks` style permissions to configure. ### Step 4: Enable Global Tauri API[​](#step-4-enable-global-tauri-api "Direct link to Step 4: Enable Global Tauri API") Make sure `withGlobalTauri` is enabled in `src-tauri/tauri.conf.json`: ``` { "app": { "withGlobalTauri": true, "windows": [ { "title": "My App", "width": 800, "height": 600 } ], "security": { "capabilities": ["default"] } } } ``` ### Step 5: Import Frontend Plugin[​](#step-5-import-frontend-plugin "Direct link to Step 5: Import Frontend Plugin") Import the frontend plugin in your main frontend entry file (usually `index.html` or `main.ts`): **In HTML:** ``` ``` **In TypeScript/JavaScript:** ``` import '@wdio/tauri-plugin'; ``` This import must happen **before** your tests run. The plugin auto-initializes on import and sets up: * `window.wdioTauri` API * Console forwarding * Invoke interception for mocking * Event listeners for backend logs ### Step 6: Build and Verify[​](#step-6-build-and-verify "Direct link to Step 6: Build and Verify") Build your Tauri app: ``` cd src-tauri cargo build --release ``` The build should complete successfully without errors about the plugin. ## Verifying the Plugin Installation[​](#verifying-the-plugin-installation "Direct link to Verifying the Plugin Installation") ### Method 1: Check Browser Console[​](#method-1-check-browser-console "Direct link to Method 1: Check Browser Console") After starting your test session, the plugin will log initialization messages: ``` [WDIO Plugin] Initializing... [WDIO Plugin] Successfully initialized ``` ### Method 2: Test Plugin Availability[​](#method-2-test-plugin-availability "Direct link to Method 2: Test Plugin Availability") In a test, check if the plugin is available: ``` it('should have plugin available', async () => { const available = await browser.tauri.isTauriApiAvailable?.(); expect(available).toBe(true); }); ``` ### Method 3: Try Execute API[​](#method-3-try-execute-api "Direct link to Method 3: Try Execute API") The execute API will work if the plugin is properly installed: ``` it('should execute JavaScript', async () => { const result = await browser.tauri.execute(() => { return window.location.href; }); expect(result).toBeDefined(); }); ``` ## Troubleshooting Plugin Issues[​](#troubleshooting-plugin-issues "Direct link to Troubleshooting Plugin Issues") ### "Tauri plugin not available" Error[​](#tauri-plugin-not-available-error "Direct link to \"Tauri plugin not available\" Error") This means the plugin is not detected. Check: 1. **Plugin registered in Rust** ``` .plugin(tauri_plugin_wdio::init()) ``` 2. **Frontend import present** ``` import '@wdio/tauri-plugin'; ``` 3. **`withGlobalTauri` enabled** ``` { "app": { "withGlobalTauri": true } } ``` 4. **Permissions configured** Check that `"wdio:default"` is in your capabilities permissions. ### "window\.wdioTauri is undefined" Error[​](#windowwdiotauri-is-undefined-error "Direct link to \"window.wdioTauri is undefined\" Error") The frontend plugin didn't initialize. Make sure: 1. The import statement is in your **main entry point**, before tests run 2. You're not running in an iframe or separate context 3. The app has time to initialize (add a small delay if needed): ``` it('should have wdioTauri', async () => { // Give plugin time to initialize await browser.pause(500); const hasPlugin = 'wdioTauri' in window; expect(hasPlugin).toBe(true); }); ``` ### Mocking Doesn't Work[​](#mocking-doesnt-work "Direct link to Mocking Doesn't Work") Make sure: 1. Plugin is installed and available (see verification methods above) 2. You're using `browser.tauri.mock()`, not trying to mock directly 3. The mock is set up **before** calling the command: ``` // ✅ Correct const mock = await browser.tauri.mock('my_command'); await mock.mockReturnValue('test'); await browser.tauri.execute(({ core }) => core.invoke('my_command')); // ❌ Wrong - mock set up after calling command await browser.tauri.execute(({ core }) => core.invoke('my_command')); const mock = await browser.tauri.mock('my_command'); ``` ### Plugin Compilation Errors[​](#plugin-compilation-errors "Direct link to Plugin Compilation Errors") If you get Rust compilation errors: 1. **Ensure Rust toolchain is up to date** ``` rustup update ``` 2. **Clear Cargo cache** ``` cd src-tauri cargo clean cargo build --release ``` 3. **Check Tauri version compatibility** * tauri-plugin-wdio requires **Tauri v2.0+** * If you're on Tauri v1, this plugin won't work 4. **Check dependency versions** ``` tauri = { version = "2", ... } tauri-plugin-wdio = "1" ``` ## Plugin Architecture[​](#plugin-architecture "Direct link to Plugin Architecture") ### How It Works[​](#how-it-works "Direct link to How It Works") The plugin consists of two parts: 1. **Rust Backend** (`packages/tauri-plugin/src/`) * Provides Tauri commands: `execute`, `log_frontend`, `debug_plugin` * Handles script execution via `window.eval()` * Manages result serialization 2. **Frontend JavaScript** (`packages/tauri-plugin/guest-js/`) * Auto-initializes on import * Exposes `window.wdioTauri` API * Intercepts `window.__TAURI__.core.invoke` for mocking * Forwards console logs to Tauri logger ### Plugin Lifecycle[​](#plugin-lifecycle "Direct link to Plugin Lifecycle") When you import `@wdio/tauri-plugin`: 1. Plugin code loads and detects Tauri APIs 2. Sets up console forwarding 3. Sets up invoke interception for mocking 4. Registers event listeners for backend logs 5. Exposes `window.wdioTauri` object 6. On page unload, cleans up listeners and timers ### Permissions Detail[​](#permissions-detail "Direct link to Permissions Detail") The `wdio:default` permission includes every plugin command: * `wdio:allow-execute` - Execute JavaScript in frontend context * `wdio:allow-log-frontend` - Forward frontend logs * `wdio:allow-debug-plugin` - Debug plugin state * `wdio:allow-get-active-window-label` - Get active window label * `wdio:allow-get-window-states` - Get window states * `wdio:allow-list-windows` - List windows Mocking is implemented entirely on the JavaScript side via invoke interception, so there are no mock-related Rust permissions. If you want a smaller surface, you can grant a subset — `wdio:allow-execute` alone is enough to run scripts and use the mocking API: ``` { "permissions": [ "wdio:allow-execute" ] } ``` ## Production Considerations[​](#production-considerations "Direct link to Production Considerations") ### Should I Include the Plugin in Production?[​](#should-i-include-the-plugin-in-production "Direct link to Should I Include the Plugin in Production?") **No**, the plugin is **test-only**. For production builds: 1. **Conditionally register the plugin** ``` fn main() { let mut builder = tauri::Builder::default(); #[cfg(debug_assertions)] { builder = builder.plugin(tauri_plugin_wdio::init()); } builder .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` 2. **Or use feature flags** ``` [features] wdio = ["dep:tauri-plugin-wdio"] [dependencies] tauri-plugin-wdio = { version = "1", optional = true } ``` ``` fn main() { let mut builder = tauri::Builder::default(); #[cfg(feature = "wdio")] { builder = builder.plugin(tauri_plugin_wdio::init()); } builder .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` 3. **Build release without the plugin** ``` cargo build --release ``` ### Plugin Security[​](#plugin-security "Direct link to Plugin Security") The plugin: * Only accepts code from WebdriverIO service (not from page scripts) * Cannot access browser or system permissions without being granted * Is disabled in production builds * Requires explicit `wdio:` permissions in capabilities ## Next Steps[​](#next-steps "Direct link to Next Steps") Once the plugin is installed and verified: 1. Read [Quick Start](/docs/desktop-testing/tauri/quick-start.md) for minimal test setup 2. See [API Reference](/docs/desktop-testing/tauri/api.md) for available functions 3. Check [Usage Examples](/docs/desktop-testing/tauri/usage-examples.md) for testing patterns 4. View [Configuration](/docs/desktop-testing/tauri/configuration.md) for service options ## Plugin 2: tauri-plugin-wdio-webdriver (Optional - Embedded WebDriver)[​](#plugin-2-tauri-plugin-wdio-webdriver-optional---embedded-webdriver "Direct link to Plugin 2: tauri-plugin-wdio-webdriver (Optional - Embedded WebDriver)") This plugin embeds a W3C WebDriver HTTP server directly in your Tauri application. Use it when you want to test on macOS without CrabNebula, or when you prefer not to install an external driver. ### Requirements[​](#requirements "Direct link to Requirements") * Tauri v2.0+ * Embedded provider selected (auto-detected on macOS, or set `driverProvider: 'embedded'` / `TAURI_WEBDRIVER_PORT`) ### Installation[​](#installation "Direct link to Installation") #### 1. Add Cargo Dependency[​](#1-add-cargo-dependency "Direct link to 1. Add Cargo Dependency") ``` [target.'cfg(debug_assertions)'.dependencies] tauri-plugin-wdio-webdriver = "1" ``` #### 2. Register Plugin in Rust[​](#2-register-plugin-in-rust "Direct link to 2. Register Plugin in Rust") ``` fn main() { let builder = tauri::Builder::default(); #[cfg(debug_assertions)] let builder = builder.plugin(tauri_plugin_wdio_webdriver::init()); builder .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` #### 3. Add Permissions[​](#3-add-permissions "Direct link to 3. Add Permissions") ``` { "identifier": "default", "windows": ["main"], "permissions": [ "core:default", "core:window:default", "wdio-webdriver:default" ] } ``` > The `wdio-webdriver:default` set currently grants no IPC permissions — the plugin is an in-process HTTP server, not a command surface — but listing it ensures Tauri loads the plugin's ACL manifest. ### Configuration[​](#configuration "Direct link to Configuration") The embedded WebDriver server runs on port `4445` by default. To customize: ``` // In wdio.conf.ts services: [['@wdio/tauri-service', { driverProvider: 'embedded', embeddedPort: 4445, // Optional, defaults to 4445 }]] ``` Or via environment variable (also triggers auto-detection on Windows/Linux): ``` TAURI_WEBDRIVER_PORT=4445 npx wdio run wdio.conf.ts ``` ### How It Works[​](#how-it-works-1 "Direct link to How It Works") 1. The service spawns your Tauri app with `TAURI_WEBDRIVER_PORT` environment variable 2. The app starts an HTTP WebDriver server on that port 3. WebdriverIO connects directly to that port (no tauri-driver intermediary) 4. On test completion, the service terminates the app ### Differences from External Driver[​](#differences-from-external-driver "Direct link to Differences from External Driver") | Aspect | External Driver (official/crabnebula) | Embedded Server | | ---------------- | ------------------------------------- | ------------------------ | | Architecture | Separate driver process | HTTP server in-app | | macOS support | Requires CrabNebula | Native | | Setup complexity | Higher (driver installation) | Lower (no external deps) | | Port management | Service manages | Service + app coordinate | ## See Also[​](#see-also "Direct link to See Also") * [Tauri Plugin Documentation](https://v2.tauri.app/develop/plugins/) * [WebdriverIO Documentation](https://webdriver.io/docs) * [Tauri Application Setup](/docs/desktop-testing/tauri/quick-start.md#tauri-application-setup) --- Source: https://webdriver.io/docs/desktop-testing/tauri/platform-support.md # Platform Support Complete guide to platform-specific requirements, limitations, and WebDriver setup for Tauri testing. ## Platform Support Overview[​](#platform-support-overview "Direct link to Platform Support Overview") | Platform | Supported | WebDriver | Driver Provider | Setup | | ----------- | --------- | ------------------------ | ------------------------------------ | ------------------------- | | **Windows** | ✅ Yes | Microsoft Edge WebDriver | All (official, crabnebula, embedded) | Auto-managed | | **Linux** | ✅ Yes | WebKitWebDriver | All (official, crabnebula, embedded) | Manual install | | **macOS** | ✅ Yes | Built-in | `'embedded'`, `'crabnebula'` | No external driver needed | ## Windows[​](#windows "Direct link to Windows") ### WebDriver: Microsoft Edge WebDriver[​](#webdriver-microsoft-edge-webdriver "Direct link to WebDriver: Microsoft Edge WebDriver") Windows uses the **Microsoft Edge WebDriver** (msedgedriver.exe) which communicates with the WebView2 runtime embedded in your Tauri app. #### Auto-Management (Recommended)[​](#auto-management-recommended "Direct link to Auto-Management (Recommended)") The service automatically: 1. Detects the WebView2 version in your Tauri binary 2. Downloads the matching MSEdgeDriver if missing 3. Handles version mismatches **Configuration:** ``` services: [['@wdio/tauri-service', { autoDownloadEdgeDriver: true, // Default: true }]], ``` #### Manual Setup[​](#manual-setup "Direct link to Manual Setup") If auto-management fails: 1. **Detect your WebView2 version** * Build your app: `cargo build --release` * Right-click the .exe → Properties → Details * Note the "File version" (e.g., 143.0.3650.139) 2. **Download matching MSEdgeDriver** * Visit [Microsoft Edge WebDriver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) * Download the version matching your WebView2 * Extract to PATH or specify in config 3. **Configure WebdriverIO** ``` services: [['@wdio/tauri-service', { autoDownloadEdgeDriver: false, tauriDriverPort: 4444, }]], ``` #### Troubleshooting Windows Issues[​](#troubleshooting-windows-issues "Direct link to Troubleshooting Windows Issues") **"This version of Microsoft Edge WebDriver only supports Microsoft Edge version X"** Version mismatch between driver and WebView2. Solutions: 1. Enable auto-download (default): ``` autoDownloadEdgeDriver: true ``` 2. Or manually match versions: * Check WebView2 version in your binary * Download corresponding MSEdgeDriver * Update PATH or config **"msedgedriver.exe not found"** 1. Check if installed: ``` where msedgedriver.exe ``` 2. Install or download from [Microsoft Edge WebDriver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) 3. Add to PATH or disable auto-download and specify manually ### Alternative Driver Providers on Windows[​](#alternative-driver-providers-on-windows "Direct link to Alternative Driver Providers on Windows") The default Windows setup uses `tauri-driver` + MSEdgeDriver (the `'official'` provider), but both other providers also work on Windows: | Provider | Notes | | -------------- | ---------------------------------------------------------------------- | | `'official'` | Default — uses tauri-driver + MSEdgeDriver, auto-managed | | `'embedded'` | Requires `tauri-plugin-wdio-webdriver` in your app; no external driver | | `'crabnebula'` | Requires a paid CrabNebula API key; cross-platform alternative | Use `'embedded'` if you want a consistent setup across Windows, Linux, and macOS without managing external drivers. Use `'crabnebula'` if you already have a CrabNebula subscription. ### Windows-Specific Features[​](#windows-specific-features "Direct link to Windows-Specific Features") * ✅ Full Tauri API support * ✅ Command execution * ✅ Mocking with tauri-plugin-wdio * ✅ Log capture (frontend and backend) * ✅ Screenshot capture * ✅ File operations * ✅ Multiremote testing ### Requirements[​](#requirements "Direct link to Requirements") * **Visual C++ Build Tools** or Visual Studio * **Rust toolchain** (for building Tauri apps) * **Node.js 18+** ## Linux[​](#linux "Direct link to Linux") ### WebDriver: WebKitWebDriver[​](#webdriver-webkitwebdriver "Direct link to WebDriver: WebKitWebDriver") Linux uses **WebKitWebDriver** (WebKitGTK) which communicates with the Tauri app's WebKit runtime. #### Installation by Distribution[​](#installation-by-distribution "Direct link to Installation by Distribution") **Debian/Ubuntu (✅ Supported)** ``` sudo apt-get update sudo apt-get install -y webkit2gtk-driver # Verify installation which webkit2gtk-driver ``` **Fedora 40+ (✅ Supported)** ``` sudo dnf install -y webkit2gtk-driver # Verify installation which webkit2gtk-driver ``` **Arch Linux (✅ Supported)** WebKitWebDriver is provided by webkit2gtk: ``` sudo pacman -S webkit2gtk-4.1 # Verify installation which webkit2gtk-driver ``` **Void Linux (✅ Supported)** ``` sudo xbps-install -y webkit2gtk-devel # Verify installation which webkit2gtk-driver ``` **Alpine Linux (❌ Not Supported)** Alpine uses musl C library which is incompatible with Tauri app building. Alpine can only be used as a **runtime container**, not for building Tauri apps. **CentOS Stream / RHEL (❌ Not Supported)** * **Stream 9 / RHEL 9**: glib 2.68 is too old (requires 2.70+) * **Stream 10 / RHEL 10**: WebKitGTK intentionally removed due to security vulnerabilities **Recommendation:** Use **Fedora 40+** for RHEL-based distributions. **openSUSE / SUSE (❌ Not Supported)** No official WebKitWebDriver package. Building from source is complex and not recommended. **Other Distributions** Check if webkit2gtk is available: ``` # Debian-based apt search webkit2gtk-driver # RedHat-based dnf search webkit2gtk-driver # Pacman-based pacman -Ss webkit2gtk ``` #### Headless Testing[​](#headless-testing "Direct link to Headless Testing") To run tests without a display (CI/CD environments): **With Xvfb (X Virtual Framebuffer)** Install Xvfb: ``` sudo apt-get install -y xvfb # Debian/Ubuntu sudo dnf install -y xvfb # Fedora ``` Run tests: ``` xvfb-run -a npm run test:e2e ``` Or automatically via WebdriverIO (requires wdio 9.19.1+): ``` services: [['@wdio/tauri-service', { // Xvfb is auto-detected and used if available }]], ``` **With Wayland** If you're on a Wayland desktop: ``` # Set XWayland if needed export GDK_BACKEND=x11 npm run test:e2e ``` #### Troubleshooting Linux Issues[​](#troubleshooting-linux-issues "Direct link to Troubleshooting Linux Issues") **"webkit2gtk-driver not found"** 1. Verify installation: ``` which webkit2gtk-driver ``` 2. If not found, install for your distribution (see above) 3. Add to PATH if in non-standard location: ``` export PATH="/path/to/driver:$PATH" ``` **"X11 connection refused" or "Cannot open display"** Your system doesn't have a display server. Solutions: 1. **Use Xvfb** ``` xvfb-run -a npm run test:e2e ``` 2. **Or use Docker with X11 forwarding** ``` docker run -e DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix my-image ``` 3. **Or enable headless mode** (if supported): ``` export WAYLAND_DISPLAY="" npm run test:e2e ``` **"glib version too old"** CentOS Stream / RHEL issue. Use **Fedora 40+** instead. **"Permission denied" when installing webkit2gtk** Use `sudo` for package installation: ``` sudo apt-get install webkit2gtk-driver ``` ### Alternative Driver Providers on Linux[​](#alternative-driver-providers-on-linux "Direct link to Alternative Driver Providers on Linux") The default Linux setup uses `tauri-driver` + WebKitWebDriver (the `'official'` provider), but both other providers also work on Linux: | Provider | Notes | | -------------- | ---------------------------------------------------------------------- | | `'official'` | Default — uses tauri-driver + WebKitWebDriver, requires manual install | | `'embedded'` | Requires `tauri-plugin-wdio-webdriver` in your app; no external driver | | `'crabnebula'` | Requires a paid CrabNebula API key; cross-platform alternative | Use `'embedded'` if you want a consistent setup across Windows, Linux, and macOS without managing external drivers. Use `'crabnebula'` if you already have a CrabNebula subscription. ### Linux-Specific Features[​](#linux-specific-features "Direct link to Linux-Specific Features") * ✅ Full Tauri API support * ✅ Command execution * ✅ Mocking with tauri-plugin-wdio * ✅ Log capture (frontend and backend) * ✅ Screenshot capture * ✅ File operations * ✅ Headless testing with Xvfb * ✅ Multiremote testing ### Requirements[​](#requirements-1 "Direct link to Requirements") * **WebKitGTK development libraries** (webkit2gtk-driver) — only needed for `'official'` provider * **Xvfb** (optional, for headless testing) * **Rust toolchain** (for building Tauri apps) * **Node.js 18+** ## macOS[​](#macos "Direct link to macOS") > **Note:** macOS testing is supported natively via the embedded WebDriver provider. On macOS the service **auto-detects** the embedded provider — no explicit `driverProvider` configuration is needed. ### Embedded Provider (Recommended)[​](#embedded-provider-recommended "Direct link to Embedded Provider (Recommended)") The embedded WebDriver provider uses `tauri-plugin-wdio-webdriver` to provide native macOS support without requiring CrabNebula. #### Requirements[​](#requirements-2 "Direct link to Requirements") 1. Install `tauri-plugin-wdio-webdriver` in your Tauri app: ``` cd src-tauri && cargo add tauri-plugin-wdio-webdriver ``` 2. Register the plugin in your Rust code (debug builds only): ``` fn main() { let builder = tauri::Builder::default(); #[cfg(debug_assertions)] let builder = builder.plugin(tauri_plugin_wdio_webdriver::init()); builder .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` 3. Add permissions in `src-tauri/capabilities/default.json`: ``` { "permissions": [ "core:default", "core:window:default", "wdio-webdriver:default" ] } ``` 4. Configure WebdriverIO — no explicit `driverProvider` needed on macOS: ``` services: [['@wdio/tauri-service', { // driverProvider auto-detected as 'embedded' on macOS }]] ``` You can also set it explicitly if you prefer: ``` services: [['@wdio/tauri-service', { driverProvider: 'embedded', }]] ``` #### Advantages[​](#advantages "Direct link to Advantages") * ✅ No external driver needed (no CrabNebula subscription) * ✅ Works natively on macOS — auto-detected, zero config * ✅ Same plugin setup works on Windows and Linux too * ✅ Simpler CI/CD configuration See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) for detailed setup instructions. ### CrabNebula[​](#crabnebula "Direct link to CrabNebula") [CrabNebula](https://crabnebula.dev)'s `@crabnebula/tauri-driver` is a cross-platform alternative that works on Windows, Linux, and macOS. It's a fork of the official tauri-driver with added macOS support via a proprietary WebDriver implementation. #### Platform Support[​](#platform-support "Direct link to Platform Support") | Platform | Supported | Requirements | | ----------- | --------- | ------------------------------------------------ | | **Windows** | ✅ Yes | `@crabnebula/tauri-driver` | | **Linux** | ✅ Yes | `@crabnebula/tauri-driver` + `webkit2gtk-driver` | | **macOS** | ✅ Yes | `@crabnebula/tauri-driver` + `CN_API_KEY` | > **Note:** `CN_API_KEY` is only required for macOS. Windows and Linux work without an API key. #### When to Use CrabNebula[​](#when-to-use-crabnebula "Direct link to When to Use CrabNebula") * You already have a CrabNebula subscription * You want a single driver configuration across all platforms * You need macOS testing without the embedded provider #### Requirements[​](#requirements-3 "Direct link to Requirements") 1. **@crabnebula/tauri-driver** npm package (all platforms) 2. **@crabnebula/test-runner-backend** npm package (macOS only, for local testing) 3. **CN\_API\_KEY** environment variable (macOS only) 4. **tauri-plugin-automation** in your Tauri app (macOS only) 5. **webkit2gtk-driver** (Linux only — see Linux section for installation) #### Setup[​](#setup "Direct link to Setup") 1. Install CrabNebula packages: ``` npm install -D @crabnebula/tauri-driver # For macOS, also install: npm install -D @crabnebula/test-runner-backend ``` 2. **For macOS only** — add the automation plugin to your Tauri app: ``` cd src-tauri && cargo add tauri-plugin-automation ``` 3. **For macOS only** — register the plugin (debug builds only): ``` let mut builder = tauri::Builder::default(); #[cfg(debug_assertions)] { builder = builder.plugin(tauri_plugin_automation::init()); } ``` 4. **For macOS only** — set your API key: ``` export CN_API_KEY="your-api-key" ``` 5. Configure WebdriverIO: ``` services: [['@wdio/tauri-service', { driverProvider: 'crabnebula', }]] ``` See the [CrabNebula Setup Guide](/docs/desktop-testing/tauri/crabnebula-setup.md) for detailed instructions. ### Alternatives for macOS[​](#alternatives-for-macos "Direct link to Alternatives for macOS") If you cannot use the embedded provider or CrabNebula, consider: 1. **Cross-Platform Testing** * Develop on macOS, run automated tests on Linux/Windows * Perform manual QA on macOS 2. **Web Version** * Deploy a web version of your app * Test with traditional WebdriverIO setup ### Building on macOS[​](#building-on-macos "Direct link to Building on macOS") Build and test Tauri apps on macOS: ``` npm install npm run tauri build npx wdio run wdio.conf.ts ``` The service auto-detects the embedded provider on macOS. Make sure `tauri-plugin-wdio-webdriver` is installed and registered in your app. ### Example CI Configuration[​](#example-ci-configuration "Direct link to Example CI Configuration") If you're developing on macOS but testing on Linux: ``` # .github/workflows/test.yml jobs: test-linux: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 - uses: dtolnay/rust-toolchain@stable - run: npm install - run: npm run tauri build - run: npm run test:e2e build-macos: runs-on: macos-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 - uses: dtolnay/rust-toolchain@stable - run: npm install - run: npm run tauri build # No test step - just build verification ``` ## Cross-Platform Tips[​](#cross-platform-tips "Direct link to Cross-Platform Tips") ### CI/CD Matrix[​](#cicd-matrix "Direct link to CI/CD Matrix") Test on multiple platforms: ``` // wdio.conf.ts - Example for matrix testing export const config = { onPrepare: async (config, specs) => { const platform = process.platform; const arch = process.arch; console.log(`Testing on ${platform}-${arch}`); if (platform === 'win32') { config.services = [['@wdio/tauri-service', { autoDownloadEdgeDriver: true, }]]; } else if (platform === 'linux') { config.services = [['@wdio/tauri-service', { // WebKitWebDriver auto-detected }]]; } else if (platform === 'darwin') { config.services = [['@wdio/tauri-service', { // embedded provider auto-detected on macOS }]]; } }, }; ``` ### Platform-Specific Tests[​](#platform-specific-tests "Direct link to Platform-Specific Tests") Skip tests on unsupported platforms: ``` describe('Platform-specific features', () => { it('should handle Windows path format', function() { if (process.platform !== 'win32') { this.skip(); } // Windows-specific test }); it('should handle Linux file permissions', function() { if (process.platform !== 'linux') { this.skip(); } // Linux-specific test }); }); ``` ## Summary[​](#summary "Direct link to Summary") * **Windows** - Fully supported with auto-managed Edge WebDriver ✅ * **Linux** - Fully supported with manual WebKitWebDriver setup ✅ * **macOS** - Fully supported via embedded WebDriver (no external drivers needed) ✅ Choose any platform for automated testing. Use `'embedded'` driver provider for the simplest setup. ## See Also[​](#see-also "Direct link to See Also") * [Quick Start](/docs/desktop-testing/tauri/quick-start.md) for setup instructions * [Edge WebDriver Windows](/docs/desktop-testing/tauri/edge-webdriver-windows.md) for Windows-specific details * [Troubleshooting](/docs/desktop-testing/tauri/troubleshooting.md) for common issues * [Tauri Platform-Specific Docs](https://v2.tauri.app/guides/develop/development-cycle/) --- Source: https://webdriver.io/docs/desktop-testing/tauri/usage-examples.md # Usage Examples Practical examples for testing Tauri applications with WebdriverIO. ## Basic Usage[​](#basic-usage "Direct link to Basic Usage") ### Element Interactions[​](#element-interactions "Direct link to Element Interactions") Standard WebDriver element interactions work with Tauri apps: ``` describe('Tauri App Interactions', () => { it('should interact with form elements', async () => { // Find elements by selector const input = await browser.$('input[name="username"]'); await input.setValue('test_user'); const button = await browser.$('button[type="submit"]'); await button.click(); // Wait for element and check visibility const result = await browser.$('.result'); await result.waitForDisplayed(); const text = await result.getText(); expect(text).toBe('Success!'); }); it('should handle multiple elements', async () => { const buttons = await browser.$$('button'); expect(buttons).toHaveLength(5); // Interact with each button for (const button of buttons) { const text = await button.getText(); console.log('Button text:', text); } }); it('should navigate and wait', async () => { // Navigate within the app const link = await browser.$('a[href="#settings"]'); await link.click(); // Wait for page to load const settings = await browser.$('.settings-panel'); await settings.waitForDisplayed({ timeout: 5000 }); }); }); ``` ## Tauri API Access[​](#tauri-api-access "Direct link to Tauri API Access") ### Execute JavaScript in App Context[​](#execute-javascript-in-app-context "Direct link to Execute JavaScript in App Context") Use `browser.tauri.execute()` to run JavaScript with access to Tauri APIs: ``` describe('Tauri API Access', () => { it('should access window location', async () => { const url = await browser.tauri.execute(() => { return window.location.href; }); console.log('Current URL:', url); }); it('should access Tauri invoke API', async () => { const result = await browser.tauri.execute(({ core }) => { return core.invoke('get_config'); }); expect(result).toBeDefined(); }); it('should use async operations', async () => { const data = await browser.tauri.execute(async ({ core }) => { const user = await core.invoke('get_user'); const permissions = await core.invoke('get_user_permissions', { userId: user.id }); return { user, permissions }; }); expect(data.user).toBeDefined(); expect(data.permissions).toBeInstanceOf(Array); }); it('should execute with parameters', async () => { const username = 'test_user'; const result = await browser.tauri.execute( (args) => { return { received: args.username }; }, { username } ); expect(result.received).toBe('test_user'); }); it('should handle errors', async () => { try { await browser.tauri.execute(() => { throw new Error('Test error'); }); } catch (error) { expect(error.message).toContain('Test error'); } }); }); ``` ## Mocking Tauri Commands[​](#mocking-tauri-commands "Direct link to Mocking Tauri Commands") ### Mock Backend Commands[​](#mock-backend-commands "Direct link to Mock Backend Commands") Mock Tauri commands to test frontend behavior without backend: ``` describe('Command Mocking', () => { it('should mock a simple command', async () => { // Set up mock const mock = await browser.tauri.mock('get_app_version'); await mock.mockReturnValue('1.2.3'); // Call the mocked command const version = await browser.tauri.execute(({ core }) => { return core.invoke('get_app_version'); }); expect(version).toBe('1.2.3'); }); it('should mock command with arguments', async () => { const mock = await browser.tauri.mock('get_user'); await mock.mockReturnValue({ id: 1, name: 'John Doe' }); const user = await browser.tauri.execute(({ core }) => { return core.invoke('get_user', { userId: 123 }); }); expect(user).toEqual({ id: 1, name: 'John Doe' }); }); it('should track mock calls', async () => { const mock = await browser.tauri.mock('save_data'); await mock.mockReturnValue({ success: true }); // Call the command multiple times await browser.tauri.execute(({ core }) => { core.invoke('save_data', { data: 'test1' }); core.invoke('save_data', { data: 'test2' }); }); expect(mock.calls.length).toBeGreaterThanOrEqual(2); }); it('should mock command with implementation', async () => { const mock = await browser.tauri.mock('calculate'); await mock.mockImplementation((a, b) => { return a + b; }); const result = await browser.tauri.execute(({ core }) => { return core.invoke('calculate', { a: 5, b: 3 }); }); expect(result).toBe(8); }); it('should handle errors in mocks', async () => { const mock = await browser.tauri.mock('risky_operation'); await mock.mockRejectedValue(new Error('Operation failed')); try { await browser.tauri.execute(({ core }) => { return core.invoke('risky_operation'); }); } catch (error) { expect(error.message).toBe('Operation failed'); } }); it('should restore mocks after test', async () => { const mock = await browser.tauri.mock('get_data'); await mock.mockReturnValue({ mocked: true }); // Restore original behavior await mock.mockRestore(); // Now calls the real command const result = await browser.tauri.execute(({ core }) => { return core.invoke('get_data'); }); // Result should be from actual backend expect(result).toBeDefined(); }); }); ``` ## Testing Custom Commands[​](#testing-custom-commands "Direct link to Testing Custom Commands") ### Invoke Custom Tauri Commands[​](#invoke-custom-tauri-commands "Direct link to Invoke Custom Tauri Commands") Test commands you've defined in your Tauri backend: ``` describe('Custom Tauri Commands', () => { it('should call custom command with simple return', async () => { const greeting = await browser.tauri.execute(({ core }) => { return core.invoke('greet', { name: 'Tauri' }); }); expect(greeting).toBe('Hello, Tauri!'); }); it('should call command returning object', async () => { const config = await browser.tauri.execute(({ core }) => { return core.invoke('get_config'); }); expect(config).toHaveProperty('version'); expect(config).toHaveProperty('isDev'); }); it('should handle command with file paths', async () => { const result = await browser.tauri.execute(({ core }) => { return core.invoke('read_project_file', { path: './src/main.rs' }); }); expect(result).toContain('fn main()'); }); it('should handle command timeout', async () => { try { await browser.tauri.execute(async ({ core }) => { // Simulate a slow operation return core.invoke('slow_operation'); }); } catch (error) { // Handle timeout console.log('Command timed out:', error.message); } }); }); ``` ## Testing with Logs[​](#testing-with-logs "Direct link to Testing with Logs") ### Capture and Verify Logs[​](#capture-and-verify-logs "Direct link to Capture and Verify Logs") Test that your app produces expected logs: ``` describe('Log Capture', () => { before(async () => { // Enable log capture in wdio.conf.ts: // captureBackendLogs: true, // captureFrontendLogs: true, // backendLogLevel: 'debug', // frontendLogLevel: 'debug', }); it('should verify console logs', async () => { // Clear previous logs const logs = await browser.getLogs('browser'); // Perform action that logs await browser.$('button').click(); // Get new logs const newLogs = await browser.getLogs('browser'); const hasExpectedLog = newLogs.some(log => log.message.includes('Button clicked') ); expect(hasExpectedLog).toBe(true); }); it('should track debug logs', async () => { await browser.tauri.execute(() => { console.debug('Debug message from test'); }); const logs = await browser.getLogs('browser'); const debugLogs = logs.filter(log => log.level === 'DEBUG'); expect(debugLogs.length).toBeGreaterThan(0); }); }); ``` ## Multiremote Testing[​](#multiremote-testing "Direct link to Multiremote Testing") ### Testing Multiple App Instances[​](#testing-multiple-app-instances "Direct link to Testing Multiple App Instances") Test interactions between multiple Tauri app instances: ``` describe('Multiremote - Multiple App Instances', () => { it('should interact with both app instances', async () => { // Access first app instance const app1Button = await browser.app1.$('button[data-testid="send"]'); await app1Button.click(); // Access second app instance const app2Input = await browser.app2.$('input[data-testid="message"]'); const text = await app2Input.getValue(); expect(text).toBe('Message from app1'); }); it('should mock different commands per instance', async () => { // Mock command on first app const mock1 = await browser.app1.tauri.mock('get_user'); await mock1.mockReturnValue({ id: 1, name: 'User1' }); // Mock different value on second app const mock2 = await browser.app2.tauri.mock('get_user'); await mock2.mockReturnValue({ id: 2, name: 'User2' }); // Verify each app gets its mocked value const user1 = await browser.app1.tauri.execute(({ core }) => { return core.invoke('get_user'); }); const user2 = await browser.app2.tauri.execute(({ core }) => { return core.invoke('get_user'); }); expect(user1.id).toBe(1); expect(user2.id).toBe(2); }); it('should clear mocks independently', async () => { // Set up mocks on both instances const mock1 = await browser.app1.tauri.mock('get_config'); await mock1.mockReturnValue({ version: '1.0.0' }); const mock2 = await browser.app2.tauri.mock('get_config'); await mock2.mockReturnValue({ version: '2.0.0' }); // Clear only app1's mocks await browser.app1.tauri.clearAllMocks(); // app1 now calls real command, app2 still mocked const config2 = await browser.app2.tauri.execute(({ core }) => { return core.invoke('get_config'); }); expect(config2.version).toBe('2.0.0'); }); }); ``` ## Multi-Window Testing[​](#multi-window-testing "Direct link to Multi-Window Testing") ### Testing Multiple Tauri Windows[​](#testing-multiple-tauri-windows "Direct link to Testing Multiple Tauri Windows") Test interactions with multiple windows in a single Tauri app: ``` import { withExecuteOptions } from '@wdio/tauri-service'; describe('Multi-Window Testing', () => { it('should list available windows', async () => { const windows = await browser.tauri.listWindows(); console.log('Available windows:', windows); expect(windows).toContain('main'); expect(windows).toContain('settings'); }); it('should switch between windows', async () => { // Start in main window const mainContent = await browser.tauri.execute(() => { return document.querySelector('h1')?.textContent; }); expect(mainContent).toBe('Main Window'); // Switch to settings window await browser.tauri.switchWindow('settings'); // Now executing in settings context const settingsContent = await browser.tauri.execute(() => { return document.querySelector('h1')?.textContent; }); expect(settingsContent).toBe('Settings'); // Switch back to main await browser.tauri.switchWindow('main'); }); it('should execute in specific window without switching', async () => { // Use per-call windowLabel to target a specific window const result = await browser.tauri.execute( (tauri) => tauri.core.invoke('get_window_data'), withExecuteOptions({ windowLabel: 'popup' }) ); expect(result).toEqual({ source: 'popup' }); }); it('should handle non-existent window gracefully', async () => { await expect(browser.tauri.switchWindow('nonexistent')).rejects.toThrow( 'Window label "nonexistent" not found. Available windows: main, settings, popup' ); }); }); ``` **Configuration:** You can also set a default window in your WDIO config: ``` // wdio.conf.ts export const config = { capabilities: [{ browserName: 'tauri', 'wdio:tauriServiceOptions': { windowLabel: 'settings', // Default to settings window }, }], }; ``` ## Common Testing Patterns[​](#common-testing-patterns "Direct link to Common Testing Patterns") ### Wait for Async Operations[​](#wait-for-async-operations "Direct link to Wait for Async Operations") ``` it('should wait for async data load', async () => { // Trigger data fetch const loadButton = await browser.$('button[data-testid="load"]'); await loadButton.click(); // Wait for loading state to disappear const spinner = await browser.$('.loading-spinner'); await spinner.waitForDisplayed({ reverse: true, timeout: 5000 }); // Verify data appeared const data = await browser.$('.data-content'); expect(await data.isDisplayed()).toBe(true); }); ``` ### Test Error Handling[​](#test-error-handling "Direct link to Test Error Handling") ``` it('should display error message on failure', async () => { const mock = await browser.tauri.mock('fetch_data'); await mock.mockRejectedValue(new Error('Network error')); // Trigger action that uses mocked command const button = await browser.$('button[data-testid="fetch"]'); await button.click(); // Verify error message displayed const error = await browser.$('.error-message'); await error.waitForDisplayed(); const text = await error.getText(); expect(text).toContain('Network error'); }); ``` ### Test Form Validation[​](#test-form-validation "Direct link to Test Form Validation") ``` it('should validate form input', async () => { const input = await browser.$('input[name="email"]'); // Test invalid input await input.setValue('invalid-email'); let error = await browser.$('.email-error'); expect(await error.isDisplayed()).toBe(true); // Test valid input await input.setValue('user@example.com'); error = await browser.$('.email-error'); expect(await error.isDisplayed()).toBe(false); }); ``` ### Test State Persistence[​](#test-state-persistence "Direct link to Test State Persistence") ``` it('should persist state across reload', async () => { // Set app state await browser.tauri.execute(async ({ core }) => { await core.invoke('set_user_preference', { theme: 'dark' }); }); // Reload the app (simulate) await browser.execute(() => window.location.reload()); // Verify state persisted const theme = await browser.tauri.execute(({ core }) => { return core.invoke('get_user_preference', { key: 'theme' }); }); expect(theme).toBe('dark'); }); ``` ## See Also[​](#see-also "Direct link to See Also") * [API Reference](/docs/desktop-testing/tauri/api.md) for complete API documentation * [Configuration](/docs/desktop-testing/tauri/configuration.md) for testing setup options * [Log Forwarding](/docs/desktop-testing/tauri/log-forwarding.md) for logging patterns * [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) for plugin configuration * [Troubleshooting](/docs/desktop-testing/tauri/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/tauri/log-forwarding.md # Log Forwarding Capture and forward logs from your Tauri application to WebDriverIO's logger system. ## Overview[​](#overview "Direct link to Overview") The Tauri service can capture and forward logs from both the Rust backend and frontend console to WebDriverIO's logger system. This allows you to see Tauri application logs seamlessly integrated with your test output. ## Enabling Log Forwarding[​](#enabling-log-forwarding "Direct link to Enabling Log Forwarding") Log forwarding is disabled by default. Enable it via service options: ``` // wdio.conf.ts export const config = { services: [ ['@wdio/tauri-service', { // Enable backend log capture (Rust logs from stdout) captureBackendLogs: true, // Enable frontend log capture (console logs from webview) captureFrontendLogs: true, // Minimum log level for backend logs (default: 'info') backendLogLevel: 'info', // Minimum log level for frontend logs (default: 'info') frontendLogLevel: 'info', }], ], capabilities: [ { browserName: 'tauri', 'tauri:options': { application: './path/to/app', }, }, ], }; ``` ## Log Levels[​](#log-levels "Direct link to Log Levels") Both backend and frontend log capture support the following log levels (in order of priority): * `trace` - Most verbose * `debug` - Debug information * `info` - Informational messages (default) * `warn` - Warning messages * `error` - Error messages Only logs at the configured level and above will be captured. For example, with `backendLogLevel: 'info'`, only `info`, `warn`, and `error` logs will be captured. ## Log Format[​](#log-format "Direct link to Log Format") Captured logs are formatted with context tags: * Backend logs: `[Tauri:Backend] message` * Frontend logs: `[Tauri:Frontend] message` * Multiremote logs: `[Tauri:Backend:instanceId] message` or `[Tauri:Frontend:instanceId] message` ## Backend Log Capture[​](#backend-log-capture "Direct link to Backend Log Capture") Backend log capture reads Rust logs from the Tauri application's stdout. These logs are generated using Rust's `log` crate: ``` // In your Tauri app log::info!("This is an info log"); log::warn!("This is a warning"); log::error!("This is an error"); ``` The service automatically filters out tauri-driver logs and only captures logs from your Tauri application. ## Frontend Log Capture[​](#frontend-log-capture "Direct link to Frontend Log Capture") Frontend log capture uses WebDriver's `getLogs` API to retrieve console logs from the webview: ``` // In your Tauri app frontend console.info('This is an info log'); console.warn('This is a warning'); console.error('This is an error'); ``` Frontend logs are captured periodically (every second) and before each WebDriver command to ensure all logs are captured. ## Independent Configuration[​](#independent-configuration "Direct link to Independent Configuration") Backend and frontend log capture can be configured independently: ``` services: [ ['@wdio/tauri-service', { // Only capture backend logs captureBackendLogs: true, captureFrontendLogs: false, backendLogLevel: 'debug', // Capture debug and above }], ], ``` ## Multiremote Support[​](#multiremote-support "Direct link to Multiremote Support") In multiremote scenarios, logs are captured per instance with instance IDs in the log context: ``` capabilities: { browserA: { browserName: 'tauri', 'tauri:options': { application: './path/to/app', }, }, browserB: { browserName: 'tauri', 'tauri:options': { application: './path/to/app', }, }, }, services: [ ['@wdio/tauri-service', { captureBackendLogs: true, captureFrontendLogs: true, }], ], ``` Logs will appear as: * `[Tauri:Backend:browserA] message` * `[Tauri:Frontend:browserB] message` ## Performance Considerations[​](#performance-considerations "Direct link to Performance Considerations") * Log capture is optional and disabled by default to avoid overhead * Frontend log capture uses periodic polling (every 1 second) which has minimal performance impact * Backend log parsing is efficient and non-blocking * Log level filtering reduces the number of logs processed ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### Logs not appearing[​](#logs-not-appearing "Direct link to Logs not appearing") * Ensure `captureBackendLogs` or `captureFrontendLogs` is set to `true` * Check that your log level is appropriate (logs below the configured level won't appear) * Verify logs are being written to stdout (backend) or console (frontend) ### Too many logs[​](#too-many-logs "Direct link to Too many logs") * Increase the log level (e.g., from `debug` to `info`) to filter out verbose logs * Disable log capture for one source if you only need backend or frontend logs ### Frontend logs not captured[​](#frontend-logs-not-captured "Direct link to Frontend logs not captured") * Some WebDriver implementations may not support `getLogs` API * The service will silently fail if `getLogs` is not supported * Backend logs will still work in this case ## See Also[​](#see-also "Direct link to See Also") * [Configuration](/docs/desktop-testing/tauri/configuration.md) for all service options * [Usage Examples](/docs/desktop-testing/tauri/usage-examples.md) for logging patterns * [Troubleshooting](/docs/desktop-testing/tauri/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/tauri/edge-webdriver-windows.md # Edge WebDriver on Windows ## Overview[​](#overview "Direct link to Overview") On Windows, Tauri applications use Microsoft Edge WebView2, which requires `msedgedriver.exe` for WebDriver automation. The tauri-service automatically handles Edge WebDriver version matching to prevent version mismatch errors. ## The Problem[​](#the-problem "Direct link to The Problem") Tauri tests fail on Windows when your Edge browser version doesn't match the installed msedgedriver version: ``` Error: This version of Microsoft Edge WebDriver only supports Microsoft Edge version 144. Current browser version is 143.0.3650.139 ``` ## The Solution[​](#the-solution "Direct link to The Solution") The tauri-service automatically: 1. **Detects** your Edge browser version from Windows registry 2. **Checks** if a matching msedgedriver.exe exists 3. **Downloads** the correct version if needed (enabled by default) 4. **Configures** PATH to use the downloaded driver ## Configuration[​](#configuration "Direct link to Configuration") ### Auto-Download (Recommended)[​](#auto-download-recommended "Direct link to Auto-Download (Recommended)") By default, auto-download is **enabled**. Just use the service normally: ``` // wdio.conf.js export const config = { services: [ ['tauri', { application: './path/to/your-app.exe', // autoDownloadEdgeDriver: true (default) }] ] }; ``` ### Manual Management[​](#manual-management "Direct link to Manual Management") Disable auto-download if you prefer to manage drivers yourself: ``` export const config = { services: [ ['tauri', { application: './path/to/your-app.exe', autoDownloadEdgeDriver: false }] ] }; ``` With auto-download disabled, you must ensure msedgedriver matches your Edge version manually. ## How It Works[​](#how-it-works "Direct link to How It Works") ### 1. Version Detection[​](#1-version-detection "Direct link to 1. Version Detection") The service detects Edge version from: * Windows Registry: `HKLM\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{56EB18F8-B008-4CBD-B6D2-8C97FE7E9062}` * WMIC query: `wmic datafile where name="C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" get Version` ### 2. Driver Check[​](#2-driver-check "Direct link to 2. Driver Check") Checks if msedgedriver.exe in PATH matches the detected Edge version (major version comparison). ### 3. Download & Install[​](#3-download--install "Direct link to 3. Download & Install") If mismatch detected: * Downloads msedgedriver from `https://msedgedriver.azureedge.net/{version}/` * Caches in temp directory: `%TEMP%\msedgedriver\{majorVersion}\` * Adds to process PATH for test execution ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### "Could not detect Edge version"[​](#could-not-detect-edge-version "Direct link to \"Could not detect Edge version\"") **Cause**: Edge not installed or registry keys missing **Solution**: Install Microsoft Edge from ### "Failed to download msedgedriver"[​](#failed-to-download-msedgedriver "Direct link to \"Failed to download msedgedriver\"") **Causes**: * Network/proxy issues * Microsoft's CDN temporarily unavailable * Invalid Edge version format **Solutions**: 1. Check internet connection and proxy settings 2. Retry - CDN may be temporarily down 3. Manual download from 4. Place `msedgedriver.exe` in PATH ### "Version mismatch" even after download[​](#version-mismatch-even-after-download "Direct link to \"Version mismatch\" even after download") **Cause**: Another msedgedriver.exe earlier in PATH is being used **Solution**: Check PATH order: ``` where msedgedriver.exe ``` Ensure the correct version appears first ### CI/GitHub Actions Issues[​](#cigithub-actions-issues "Direct link to CI/GitHub Actions Issues") **Symptom**: Download works locally but fails in CI **Causes**: * GitHub Actions runners may have outdated Edge * Network restrictions **Solutions**: ``` # .github/workflows/test.yml - name: Update Edge (if needed) if: runner.os == 'Windows' run: | choco upgrade microsoft-edge -y - name: Run tests run: pnpm test:e2e ``` ## Platform Behavior[​](#platform-behavior "Direct link to Platform Behavior") * **Windows**: Edge driver check runs automatically * **Linux**: Skipped (Tauri uses WebKitGTK) * **macOS**: N/A (Tauri testing not supported on macOS) ## API Reference[​](#api-reference "Direct link to API Reference") ### Service Options[​](#service-options "Direct link to Service Options") ``` interface TauriServiceOptions { /** * Automatically download and configure matching msedgedriver on Windows * @default true * @platform Windows only */ autoDownloadEdgeDriver?: boolean; } ``` ### Example Configurations[​](#example-configurations "Direct link to Example Configurations") #### Default (Auto-Download Enabled)[​](#default-auto-download-enabled "Direct link to Default (Auto-Download Enabled)") ``` services: [ ['tauri', { application: './dist/my-app.exe' }] ] ``` #### Explicit Configuration[​](#explicit-configuration "Direct link to Explicit Configuration") ``` services: [ ['tauri', { application: './dist/my-app.exe', autoDownloadEdgeDriver: true, tauriDriverPort: 4444 }] ] ``` #### Disable Auto-Download[​](#disable-auto-download "Direct link to Disable Auto-Download") ``` services: [ ['tauri', { application: './dist/my-app.exe', autoDownloadEdgeDriver: false }] ] ``` ## Manual Driver Management[​](#manual-driver-management "Direct link to Manual Driver Management") If you disable auto-download, ensure msedgedriver matches your Edge version: ### Check Edge Version[​](#check-edge-version "Direct link to Check Edge Version") ``` reg query "HKLM\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{56EB18F8-B008-4CBD-B6D2-8C97FE7E9062}" /v pv ``` ### Download Matching Driver[​](#download-matching-driver "Direct link to Download Matching Driver") 1. Visit 2. Download version matching your Edge major version 3. Extract `msedgedriver.exe` 4. Add to PATH or place in project directory ### Verify Installation[​](#verify-installation "Direct link to Verify Installation") ``` msedgedriver.exe --version # Should output: MSEdgeDriver 143.x.xxxx.xx ``` ## Development Notes[​](#development-notes "Direct link to Development Notes") ### File Structure[​](#file-structure "Direct link to File Structure") * `src/edgeDriverManager.ts` - Edge driver detection and download logic * `src/launcher.ts` - Integration point in onPrepare hook * `src/types.ts` - TypeScript interfaces ### Cache Location[​](#cache-location "Direct link to Cache Location") Downloaded drivers are cached at: ``` %TEMP%\msedgedriver\{majorVersion}\msedgedriver.exe ``` Example: `C:\Users\YourName\AppData\Local\Temp\msedgedriver\143\msedgedriver.exe` ### Logging[​](#logging "Direct link to Logging") Enable debug logs to troubleshoot: ``` export const config = { logLevel: 'debug', services: ['tauri'] }; ``` Look for logs prefixed with `[tauri-service:edge-driver]` --- Source: https://webdriver.io/docs/desktop-testing/tauri/deeplink-testing.md # Deeplink Testing The service provides the ability to test custom protocol handlers and deeplinks in your Tauri application using the `browser.tauri.triggerDeeplink()` method. ## Overview[​](#overview "Direct link to Overview") ### What is Deeplink Testing?[​](#what-is-deeplink-testing "Direct link to What is Deeplink Testing?") Deeplink testing allows you to verify that your Tauri application correctly handles custom protocol URLs (e.g., `myapp://action?param=value`). This is essential when your app registers as a protocol handler and needs to respond to URLs opened from external sources. ### When Should You Use It?[​](#when-should-you-use-it "Direct link to When Should You Use It?") Use `browser.tauri.triggerDeeplink()` when you need to: * Test that your app correctly handles custom protocol URLs * Verify deeplink parameter parsing and routing logic * Test protocol handler registration and activation * Validate deeplink-driven workflows in your application ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") ### Tauri Deep Link Plugin[​](#tauri-deep-link-plugin "Direct link to Tauri Deep Link Plugin") Your Tauri app must have the `@tauri-apps/plugin-deep-link` plugin installed and configured. See the [official Tauri deep linking documentation](https://v2.tauri.app/plugin/deep-linking/) for setup instructions. ### Protocol Registration[​](#protocol-registration "Direct link to Protocol Registration") Your app must register its custom protocol scheme in `tauri.conf.json` under the `deep-link` plugin configuration: ``` { "plugins": { "deep-link": { "desktop": { "schemes": ["myapp"] } } } } ``` ## Basic Usage[​](#basic-usage "Direct link to Basic Usage") ### Simple Example[​](#simple-example "Direct link to Simple Example") ``` describe('Protocol Handler Tests', () => { it('should handle custom protocol deeplinks', async () => { await browser.tauri.triggerDeeplink('myapp://open?file=test.txt'); await browser.waitUntil(async () => { const openedFile = await browser.tauri.execute(() => { return globalThis.lastOpenedFile; }); return openedFile === 'test.txt'; }, { timeout: 5000, timeoutMsg: 'App did not handle the deeplink' }); }); }); ``` ### Complex URL Parameters[​](#complex-url-parameters "Direct link to Complex URL Parameters") ``` it('should preserve query parameters', async () => { await browser.tauri.triggerDeeplink( 'myapp://action?param1=value1¶m2=value2&array[]=a&array[]=b' ); const receivedParams = await browser.tauri.execute(() => { return globalThis.lastDeeplinkParams; }); expect(receivedParams.param1).toBe('value1'); expect(receivedParams.param2).toBe('value2'); expect(receivedParams.array).toEqual(['a', 'b']); }); ``` ### Error Handling[​](#error-handling "Direct link to Error Handling") ``` it('should reject invalid protocols', async () => { await expect( browser.tauri.triggerDeeplink('https://example.com') ).rejects.toThrow('Invalid deeplink protocol'); }); it('should reject malformed URLs', async () => { await expect( browser.tauri.triggerDeeplink('not a url') ).rejects.toThrow('Invalid deeplink URL'); }); ``` ## Platform Behavior[​](#platform-behavior "Direct link to Platform Behavior") The service handles platform-specific differences automatically: ### Windows[​](#windows "Direct link to Windows") * Uses `cmd /c start` command to trigger the deeplink * No URL modification needed ### macOS[​](#macos "Direct link to macOS") * Uses `open` command to trigger the deeplink * No URL modification needed ### Linux[​](#linux "Direct link to Linux") * Uses `xdg-open` command to trigger the deeplink * No URL modification needed ## App Implementation[​](#app-implementation "Direct link to App Implementation") ### Frontend Deep Link Listener[​](#frontend-deep-link-listener "Direct link to Frontend Deep Link Listener") Your app needs to listen for deep links in the frontend: ``` import { listen } from '@tauri-apps/plugin-deep-link'; listen('myapp://', (url) => { console.log('Received deeplink:', url); const parsed = new URL(url); globalThis.lastDeeplinkUrl = url.toString(); const action = parsed.hostname; const params = Object.fromEntries(parsed.searchParams); switch (action) { case 'open': if (params.file) { globalThis.lastOpenedFile = params.file; } break; case 'action': globalThis.lastDeeplinkParams = params; break; } }); ``` ### Backend Handler (Optional)[​](#backend-handler-optional "Direct link to Backend Handler (Optional)") For more complex scenarios, you can also handle deep links in the Rust backend: ``` use tauri_plugin_deep_link::DeepLinkExt; #[tauri::main] async fn main() { tauri::Builder::default() .plugin(tauri_plugin_deep_link::init()) .setup(|app| { app.handle().register_uri_scheme_protocol("myapp", |request| { let url = request.url(); println!("Received deep link: {}", url); }); Ok(()) }) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` ## Common Issues[​](#common-issues "Direct link to Common Issues") ### Deeplinks Not Received in App[​](#deeplinks-not-received-in-app "Direct link to Deeplinks Not Received in App") **Symptom:** The deeplink is triggered but your app doesn't receive it. **Possible Causes and Solutions:** 1. **Protocol not registered:** * Verify `protocol.register` is set in `tauri.conf.json` * Check your app is properly registered as the handler 2. **Deep link listener not set up:** * Ensure `listen()` from `@tauri-apps/plugin-deep-link` is called * Verify the listener is set up before triggering the deeplink 3. **Deep link parsed incorrectly:** * Check console logs to see if the URL is being received * Verify URL parsing logic handles your URL format ### Invalid Deeplink Protocol Error[​](#invalid-deeplink-protocol-error "Direct link to Invalid Deeplink Protocol Error") **Symptom:** Error: "Invalid deeplink protocol: https. Expected a custom protocol." **Cause:** You're trying to use `triggerDeeplink()` with http/https/file protocols. **Solution:** Only use custom protocol schemes: ``` // Correct - custom protocol await browser.tauri.triggerDeeplink('myapp://action'); // Incorrect - web protocol await browser.tauri.triggerDeeplink('https://example.com'); // Throws error // Incorrect - file protocol await browser.tauri.triggerDeeplink('file:///path/to/file'); // Throws error ``` ### Timing Issues[​](#timing-issues "Direct link to Timing Issues") **Symptom:** Tests fail intermittently because the app hasn't processed the deeplink yet. **Solution:** Always use `waitUntil` to wait for the app to process the deeplink: ``` await browser.tauri.triggerDeeplink('myapp://action'); await browser.waitUntil(async () => { const processed = await browser.tauri.execute(() => { return globalThis.deeplinkProcessed; }); return processed === true; }, { timeout: 5000, timeoutMsg: 'App did not process the deeplink within 5 seconds' }); ``` ## See Also[​](#see-also "Direct link to See Also") * [Tauri Deep Linking Documentation](https://v2.tauri.app/plugin/deep-linking/) * [API Reference](/docs/desktop-testing/tauri/api.md) for complete method documentation * [Usage Examples](/docs/desktop-testing/tauri/usage-examples.md) for additional patterns --- Source: https://webdriver.io/docs/desktop-testing/tauri/crabnebula-setup.md # CrabNebula Setup This guide walks you through setting up CrabNebula's tauri-driver for cross-platform Tauri testing. ## Overview[​](#overview "Direct link to Overview") [CrabNebula](https://crabnebula.dev)'s `@crabnebula/tauri-driver` is a fork of the official tauri-driver that works on **Windows, Linux, and macOS**. It provides a cross-platform alternative to the official driver, with the added benefit of macOS support. ### Platform Support[​](#platform-support "Direct link to Platform Support") | Platform | Supported | Requirements | | ----------- | --------- | ------------------------------------------------ | | **Windows** | ✅ Yes | `@crabnebula/tauri-driver` | | **Linux** | ✅ Yes | `@crabnebula/tauri-driver` + `webkit2gtk-driver` | | **macOS** | ✅ Yes | `@crabnebula/tauri-driver` + `CN_API_KEY` | ### Key Points[​](#key-points "Direct link to Key Points") * **CN\_API\_KEY is only required for macOS** — Windows and Linux work without an API key * **tauri-plugin-automation is only needed for macOS** — not required on Windows or Linux * **webkit2gtk-driver is required for Linux** — same as the official driver ## When to Use CrabNebula[​](#when-to-use-crabnebula "Direct link to When to Use CrabNebula") Choose CrabNebula when: * You want a single driver configuration across all platforms (Windows, Linux, macOS) * You already have a CrabNebula subscription * You need macOS testing but cannot use the embedded provider (`tauri-plugin-wdio-webdriver`) For most users, the **embedded provider** (via `tauri-plugin-wdio-webdriver`) is the recommended choice for macOS testing — it's free, native, and requires no external services. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") ### All Platforms[​](#all-platforms "Direct link to All Platforms") 1. **Node.js 18+** and **Rust toolchain** installed 2. A **Tauri v2 application** ### Linux Only[​](#linux-only "Direct link to Linux Only") * **webkit2gtk-driver** installed (see [Linux Installation](#linux-installation)) ### macOS Only[​](#macos-only "Direct link to macOS Only") 1. **CrabNebula account** with API key (contact [CrabNebula](https://crabnebula.dev) for access) 2. **tauri-plugin-automation** installed in your Tauri app ## Installation[​](#installation "Direct link to Installation") ### Step 1: Install CrabNebula Packages[​](#step-1-install-crabnebula-packages "Direct link to Step 1: Install CrabNebula Packages") Install the npm packages as dev dependencies: ``` # All platforms npm install -D @crabnebula/tauri-driver # macOS only (for local testing) npm install -D @crabnebula/test-runner-backend ``` Or with pnpm: ``` pnpm add -D @crabnebula/tauri-driver # macOS only: pnpm add -D @crabnebula/test-runner-backend ``` ### Step 2: Linux Installation[​](#step-2-linux-installation "Direct link to Step 2: Linux Installation") On Linux, you need WebKitWebDriver (same as the official driver): ``` # Debian/Ubuntu sudo apt-get update sudo apt-get install -y webkit2gtk-driver # Fedora sudo dnf install -y webkit2gtk-driver # Arch Linux sudo pacman -S webkit2gtk-4.1 ``` Verify installation: ``` which WebKitWebDriver # Should output: /usr/bin/WebKitWebDriver ``` ### Step 3: macOS Setup (Optional)[​](#step-3-macos-setup-optional "Direct link to Step 3: macOS Setup (Optional)") For macOS testing, you need the automation plugin and API key: #### Add Automation Plugin[​](#add-automation-plugin "Direct link to Add Automation Plugin") 1. Navigate to your Tauri source directory: ``` cd src-tauri ``` 2. Add the plugin: ``` cargo add tauri-plugin-automation ``` 3. Register the plugin in your Rust code. **Important**: Only include this in debug builds: ``` // src-tauri/src/lib.rs or main.rs let mut builder = tauri::Builder::default(); // Only enable automation in debug builds #[cfg(debug_assertions)] { builder = builder.plugin(tauri_plugin_automation::init()); } builder .run(tauri::generate_context!()) .expect("error while running tauri application"); ``` > ⚠️ **Warning**: Never include the automation plugin in release builds, as it could allow external control of your application. #### Set API Key[​](#set-api-key "Direct link to Set API Key") Set your CrabNebula API key as an environment variable: ``` export CN_API_KEY="your-api-key-here" ``` For CI/CD, add this as a secret: **GitHub Actions:** ``` env: CN_API_KEY: ${{ secrets.CN_API_KEY }} ``` ### Step 4: Configure WebdriverIO[​](#step-4-configure-webdriverio "Direct link to Step 4: Configure WebdriverIO") Update your `wdio.conf.ts` to use CrabNebula: ``` export const config = { services: [ ['@wdio/tauri-service', { driverProvider: 'crabnebula', // macOS only - auto-manage the test-runner-backend (default: true) crabnebulaManageBackend: true, // macOS only - backend port (default: 3000) crabnebulaBackendPort: 3000, }] ], capabilities: [{ browserName: 'tauri', 'tauri:options': { // Path to your binary application: './src-tauri/target/release/your-app-name', } }], // ... rest of your config }; ``` ### Step 5: Build and Run[​](#step-5-build-and-run "Direct link to Step 5: Build and Run") Build your Tauri app: ``` # Debug build (required for macOS automation plugin) npm run tauri build -- --debug # Or with cargo directly cd src-tauri && cargo build ``` Run your tests: ``` npm run wdio ``` ## Platform-Specific Notes[​](#platform-specific-notes "Direct link to Platform-Specific Notes") ### Windows[​](#windows "Direct link to Windows") * No additional setup required beyond installing `@crabnebula/tauri-driver` * Edge WebDriver is auto-managed by the service ### Linux[​](#linux "Direct link to Linux") * Requires `webkit2gtk-driver` (see installation above) * For headless CI, use Xvfb: ``` xvfb-run -a npm run wdio ``` ### macOS[​](#macos "Direct link to macOS") * Requires `CN_API_KEY` environment variable * Requires `tauri-plugin-automation` in debug builds * Requires `@crabnebula/test-runner-backend` for local testing * The service auto-starts/stops the test-runner-backend ## CI/CD Configuration[​](#cicd-configuration "Direct link to CI/CD Configuration") ### GitHub Actions Example[​](#github-actions-example "Direct link to GitHub Actions Example") ``` name: E2E Tests on: [push, pull_request] jobs: test-linux: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 - uses: dtolnay/rust-toolchain@stable - name: Install WebKitWebDriver run: sudo apt-get install -y webkit2gtk-driver - name: Install dependencies run: npm install - name: Build Tauri app run: npm run tauri build -- --debug - name: Run E2E tests run: xvfb-run -a npm run test:e2e env: DRIVER_PROVIDER: crabnebula test-macos: runs-on: macos-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 - uses: dtolnay/rust-toolchain@stable - name: Install dependencies run: npm install - name: Build Tauri app run: npm run tauri build -- --debug - name: Run E2E tests env: CN_API_KEY: ${{ secrets.CN_API_KEY }} DRIVER_PROVIDER: crabnebula run: npm run test:e2e test-windows: runs-on: windows-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 - uses: dtolnay/rust-toolchain@stable - name: Install dependencies run: npm install - name: Build Tauri app run: npm run tauri build -- --debug - name: Run E2E tests env: DRIVER_PROVIDER: crabnebula run: npm run test:e2e ``` ### Conditional Testing (No API Key)[​](#conditional-testing-no-api-key "Direct link to Conditional Testing (No API Key)") If you don't have a CN\_API\_KEY in certain environments (e.g., PRs from forks): ``` - name: Run E2E tests (macOS) if: env.CN_API_KEY != '' env: CN_API_KEY: ${{ secrets.CN_API_KEY }} run: npm run test:e2e - name: Skip E2E tests (no API key) if: env.CN_API_KEY == '' run: echo "Skipping macOS tests - no CN_API_KEY available" ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### "CN\_API\_KEY is not set" (macOS)[​](#cn_api_key-is-not-set-macos "Direct link to \"CN_API_KEY is not set\" (macOS)") **Solution**: Ensure the environment variable is set: ``` echo $CN_API_KEY # Should show your API key ``` If empty, set it: ``` export CN_API_KEY="your-api-key" ``` ### "@crabnebula/tauri-driver not found"[​](#crabnebulatauri-driver-not-found "Direct link to \"@crabnebula/tauri-driver not found\"") **Solution**: Install the package: ``` npm install -D @crabnebula/tauri-driver ``` ### "tauri-plugin-automation not found" (macOS)[​](#tauri-plugin-automation-not-found-macos "Direct link to \"tauri-plugin-automation not found\" (macOS)") **Solution**: Add the plugin to your Tauri app: ``` cd src-tauri && cargo add tauri-plugin-automation ``` Then ensure it's registered in your Rust code with the `#[cfg(debug_assertions)]` guard. ### "WebKitWebDriver not found" (Linux)[​](#webkitwebdriver-not-found-linux "Direct link to \"WebKitWebDriver not found\" (Linux)") **Solution**: Install WebKitWebDriver: ``` # Debian/Ubuntu sudo apt-get install -y webkit2gtk-driver # Fedora sudo dnf install -y webkit2gtk-driver # Arch Linux sudo pacman -S webkit2gtk-4.1 ``` ### "test-runner-backend exited with code X" (macOS)[​](#test-runner-backend-exited-with-code-x-macos "Direct link to \"test-runner-backend exited with code X\" (macOS)") **Possible causes**: * Invalid or expired CN\_API\_KEY * Port 3000 already in use * macOS security restrictions **Solutions**: 1. Verify your API key is valid 2. Change the backend port: ``` crabnebulaBackendPort: 3001 ``` 3. Check System Preferences > Security & Privacy for any blocked applications ### Tests work on Windows/Linux but not macOS[​](#tests-work-on-windowslinux-but-not-macos "Direct link to Tests work on Windows/Linux but not macOS") **Checklist**: * CN\_API\_KEY is set and valid * tauri-plugin-automation is in Cargo.toml * Plugin is registered with `#[cfg(debug_assertions)]` * App is built in debug mode (target/debug/) * @crabnebula/tauri-driver is installed * @crabnebula/test-runner-backend is installed ## Advanced Configuration[​](#advanced-configuration "Direct link to Advanced Configuration") ### Custom Backend Port (macOS)[​](#custom-backend-port-macos "Direct link to Custom Backend Port (macOS)") If port 3000 is already in use: ``` services: [['@wdio/tauri-service', { driverProvider: 'crabnebula', crabnebulaBackendPort: 3001, }]] ``` ### Manual Backend Management (macOS)[​](#manual-backend-management-macos "Direct link to Manual Backend Management (macOS)") If you prefer to manage the backend yourself: ``` services: [['@wdio/tauri-service', { driverProvider: 'crabnebula', crabnebulaManageBackend: false, // You'll start/stop it manually }]] ``` Then in your test setup: ``` # Terminal 1: Start backend npx test-runner-backend # Terminal 2: Run tests export REMOTE_WEBDRIVER_URL=http://127.0.0.1:3000 npm run wdio ``` ### Custom Driver Path[​](#custom-driver-path "Direct link to Custom Driver Path") If the driver is not in node\_modules/.bin: ``` services: [['@wdio/tauri-service', { driverProvider: 'crabnebula', crabnebulaDriverPath: '/custom/path/to/tauri-driver', }]] ``` ## Migration from Official Driver[​](#migration-from-official-driver "Direct link to Migration from Official Driver") If you're already using the official tauri-driver on Windows/Linux: 1. Keep your existing configuration for Windows/Linux 2. Add CrabNebula packages as dev dependencies 3. **For macOS only**: Add the automation plugin to your Tauri app 4. **For macOS only**: Set CN\_API\_KEY in your environment 5. Update your WebdriverIO config: ``` const isMacOS = process.platform === 'darwin'; export const config = { services: [['@wdio/tauri-service', { driverProvider: 'crabnebula', // Works on all platforms // On macOS, also needs CN_API_KEY and automation plugin }]] }; ``` Or conditionally use different providers: ``` const driverProvider = process.env.DRIVER_PROVIDER || (process.platform === 'darwin' ? 'embedded' : 'official'); export const config = { services: [['@wdio/tauri-service', { driverProvider, }]] }; ``` ## Comparison: Driver Providers[​](#comparison-driver-providers "Direct link to Comparison: Driver Providers") | Feature | `official` | `crabnebula` | `embedded` | | --------------- | ---------- | ------------ | ---------- | | Windows | ✅ | ✅ | ✅ | | Linux | ✅ | ✅ | ✅ | | macOS | ❌ | ✅ | ✅ | | External driver | Yes | Yes | No | | API key | No | macOS only | No | | Plugin required | No | macOS only | Yes | | Cost | Free | Subscription | Free | **Recommendation**: Use `embedded` for the simplest cross-platform setup. Use `crabnebula` if you already have a subscription or need specific features. ## Getting Help[​](#getting-help "Direct link to Getting Help") * **CrabNebula Documentation**: * **CrabNebula Support**: Contact via their website for API key and support * **WebdriverIO Issues**: Report integration issues to the [desktop-mobile repository](https://github.com/webdriverio/desktop-mobile/issues) * **Troubleshooting Guide**: See [troubleshooting.md](/docs/desktop-testing/tauri/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/tauri/troubleshooting.md # Troubleshooting Solutions for common issues when testing Tauri applications with WebdriverIO. ## Driver Installation Issues[​](#driver-installation-issues "Direct link to Driver Installation Issues") ### "tauri-driver not found"[​](#tauri-driver-not-found "Direct link to \"tauri-driver not found\"") The service cannot find the tauri-driver executable. **Solution 1: Enable Auto-Installation** ``` services: [ ['@wdio/tauri-service', { autoInstallTauriDriver: true, // Requires Rust/cargo }] ] ``` **Solution 2: Manual Installation** ``` # Install tauri-driver via cargo cargo install tauri-driver # Verify installation which tauri-driver # macOS/Linux where tauri-driver # Windows ``` **Solution 3: Specify Path Manually** If installed in a non-standard location: ``` services: [ ['@wdio/tauri-service', { tauriDriverPath: '/custom/path/tauri-driver' }] ] ``` ### "WebKitWebDriver not found" (Linux only)[​](#webkitwebdriver-not-found-linux-only "Direct link to \"WebKitWebDriver not found\" (Linux only)") WebKitWebDriver is not installed on your Linux system. **Supported Distributions** Install for your distribution: ``` # Debian/Ubuntu sudo apt-get install -y webkit2gtk-driver # Fedora 40+ sudo dnf install -y webkit2gtk-driver # Arch Linux sudo pacman -S webkit2gtk-4.1 # Void Linux sudo xbps-install -y webkit2gtk-devel ``` **Unsupported Distributions** * **Alpine Linux**: Cannot build Tauri apps (musl incompatibility). Use Ubuntu, Debian, Fedora, or Arch instead. * **CentOS/RHEL**: Stream 9 has glib too old (requires 2.70+), Stream 10 removed WebKitGTK. Use **Fedora 40+** instead. * **openSUSE/SUSE**: No official WebKitWebDriver package. Building from source is complex and not recommended. ### "MSEdgeDriver not found" (Windows only)[​](#msedgedriver-not-found-windows-only "Direct link to \"MSEdgeDriver not found\" (Windows only)") The Edge WebDriver for Windows is not found. **Solution 1: Enable Auto-Download** ``` services: [ ['@wdio/tauri-service', { autoDownloadEdgeDriver: true // Default: true }] ] ``` **Solution 2: Manual Download** 1. Check your WebView2 version: * Build your app: `cargo build --release` * Right-click the .exe → Properties → Details * Note the "File version" (e.g., 143.0.3650.139) 2. Download matching MSEdgeDriver from [Microsoft Edge WebDriver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) 3. Add to PATH or specify in config: ``` services: [ ['@wdio/tauri-service', { autoDownloadEdgeDriver: false }] ] ``` See [Edge WebDriver (Windows)](/docs/desktop-testing/tauri/edge-webdriver-windows.md) for detailed setup. ## Plugin Issues[​](#plugin-issues "Direct link to Plugin Issues") ### "Tauri plugin not available"[​](#tauri-plugin-not-available "Direct link to \"Tauri plugin not available\"") The plugin required for testing is not detected. **Check 1: Plugin Registered in Rust** Edit `src-tauri/src/main.rs`: ``` fn main() { tauri::Builder::default() .plugin(tauri_plugin_wdio::init()) // This line required .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` **Check 2: Frontend Import Present** Ensure the import is in your HTML or main JS file: ``` ``` **Check 3: withGlobalTauri Enabled** Edit `src-tauri/tauri.conf.json`: ``` { "app": { "withGlobalTauri": true } } ``` **Check 4: Permissions Configured** Edit `src-tauri/capabilities/default.json`: ``` { "permissions": [ "core:default", "core:window:default", "wdio:default" ] } ``` **Check 5: Rebuild Application** ``` cd src-tauri cargo clean cargo build --release ``` See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) for complete installation guide. ### "window\.wdioTauri is undefined"[​](#windowwdiotauri-is-undefined "Direct link to \"window.wdioTauri is undefined\"") The frontend plugin didn't initialize. **Solution 1: Add Delay for Initialization** ``` it('should have plugin', async () => { // Wait for plugin to initialize await browser.pause(500); const hasPlugin = await browser.tauri.execute(() => { return typeof window.wdioTauri !== 'undefined'; }); expect(hasPlugin).toBe(true); }); ``` **Solution 2: Check Import Timing** Make sure the plugin is imported **before** tests run: * In `index.html` for standard Tauri apps * In your main framework entry point (main.ts, main.js) * Not inside an iframe or separate context **Solution 3: Verify Plugin Loaded** ``` it('should verify plugin is available', async () => { const available = await browser.tauri.execute(() => { return 'wdioTauri' in window; }); expect(available).toBe(true); }); ``` ### Mocking Doesn't Work[​](#mocking-doesnt-work "Direct link to Mocking Doesn't Work") Commands aren't being mocked. **Check 1: Plugin is Available** ``` const available = await browser.tauri.execute(() => { return 'wdioTauri' in window; }); if (!available) { throw new Error('Plugin not available - cannot mock'); } ``` **Check 2: Mock Set Up Before Call** ``` // ✅ Correct - mock first, then call const mock = await browser.tauri.mock('my_command'); await mock.mockReturnValue('test'); await browser.tauri.execute(({ core }) => core.invoke('my_command')); // ❌ Wrong - calling before mocking await browser.tauri.execute(({ core }) => core.invoke('my_command')); const mock = await browser.tauri.mock('my_command'); ``` **Check 3: Use Correct Command Name** ``` // Make sure command name matches exactly const mock = await browser.tauri.mock('get_user'); // Must match your command name await mock.mockReturnValue({ id: 1 }); ``` ## Application Issues[​](#application-issues "Direct link to Application Issues") ### "Application not found at path"[​](#application-not-found-at-path "Direct link to \"Application not found at path\"") The Tauri app binary cannot be found. **Solution 1: Verify Binary Exists** ``` # Windows if exist "src-tauri\target\release\my-app.exe" echo "Found" # Linux/macOS ls -la src-tauri/target/release/my-app ``` **Solution 2: Build the Application** ``` cd src-tauri cargo build --release ``` **Solution 3: Use Correct Path** Update `wdio.conf.ts`: ``` services: [ ['@wdio/tauri-service', { appBinaryPath: './src-tauri/target/release/my-app.exe', // Windows // or appBinaryPath: './src-tauri/target/release/my-app', // Linux/macOS }] ] ``` **Solution 4: Use Absolute Path** ``` import path from 'path'; services: [ ['@wdio/tauri-service', { appBinaryPath: path.resolve('./src-tauri/target/release/my-app.exe') }] ] ``` ### Commands Timing Out[​](#commands-timing-out "Direct link to Commands Timing Out") Operations take too long or timeout unexpectedly. **Solution 1: Increase Command Timeout** ``` services: [ ['@wdio/tauri-service', { commandTimeout: 60000 // 60 seconds instead of default 10s }] ] ``` **Solution 2: Increase Start Timeout** ``` services: [ ['@wdio/tauri-service', { startTimeout: 60000 // Allow more time for app to start }] ] ``` **Solution 3: Wait for App to Be Ready** ``` it('should wait for app', async () => { // Give app time to fully initialize await browser.pause(1000); // Then run test const element = await browser.$('button'); expect(element).toBeDefined(); }); ``` **Solution 4: Check App Logs** Enable logging to see what's happening: ``` services: [ ['@wdio/tauri-service', { captureBackendLogs: true, captureFrontendLogs: true, logLevel: 'debug' }] ] ``` ### "Port already in use"[​](#port-already-in-use "Direct link to \"Port already in use\"") Multiple tests are conflicting on the same port. **Solution 1: Change tauri-driver Port** ``` services: [ ['@wdio/tauri-service', { tauriDriverPort: 4445 // Instead of default 4444 }] ] ``` **Solution 2: Auto-Assign Ports for Multiremote** ``` maxInstances: 3 // Each worker gets unique port (4444, 4445, 4446) ``` **Solution 3: Kill Process Using Port** ``` # Linux/macOS lsof -ti:4444 | xargs kill -9 # Windows (PowerShell) Get-Process -Id (Get-NetTCPConnection -LocalPort 4444).OwningProcess | Stop-Process -Force ``` ## Platform Issues[​](#platform-issues "Direct link to Platform Issues") ### "No driverProvider configured and no embedded WebDriver server detected"[​](#no-driverprovider-configured-and-no-embedded-webdriver-server-detected "Direct link to \"No driverProvider configured and no embedded WebDriver server detected\"") The service cannot determine which driver provider to use. **Why this happens:** On Windows and Linux, the service does not default to any driver provider automatically. It auto-detects the embedded provider only when either: * `TAURI_WEBDRIVER_PORT` environment variable is set, or * You are on macOS **Solution 1: Use embedded provider (recommended)** 1. Install `tauri-plugin-wdio-webdriver` in your Tauri app: ``` cd src-tauri && cargo add tauri-plugin-wdio-webdriver ``` 2. Register it in your Rust code and set `TAURI_WEBDRIVER_PORT` or configure `driverProvider: 'embedded'`: ``` services: [['@wdio/tauri-service', { driverProvider: 'embedded', }]] ``` Or signal via environment variable: ``` TAURI_WEBDRIVER_PORT=4445 npx wdio run wdio.conf.ts ``` **Solution 2: Use official tauri-driver** ``` services: [['@wdio/tauri-service', { driverProvider: 'official', autoInstallTauriDriver: true, }]] ``` See [Platform Support](/docs/desktop-testing/tauri/platform-support.md) for per-platform details. ### macOS: Embedded WebDriver Not Ready[​](#macos-embedded-webdriver-not-ready "Direct link to macOS: Embedded WebDriver Not Ready") On macOS the embedded provider is auto-detected, but if the plugin is not installed the service will time out waiting for the WebDriver server. **Solution:** Ensure `tauri-plugin-wdio-webdriver` is installed and registered: ``` #[cfg(debug_assertions)] let builder = builder.plugin(tauri_plugin_wdio_webdriver::init()); ``` See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md) for the full setup guide. ## Multi-Window Issues[​](#multi-window-issues "Direct link to Multi-Window Issues") ### Window Label Not Found[​](#window-label-not-found "Direct link to Window Label Not Found") **Error:** `Window label "settings" not found. Available windows: main, dialog` **Why this happens:** The window label you specified doesn't exist in your Tauri application. **Solutions:** 1. Check available windows with `browser.tauri.listWindows()` 2. Verify the window label matches exactly (case-sensitive) 3. Ensure the window is created before your test runs ``` // Debug: List available windows const windows = await browser.tauri.listWindows(); console.log('Available:', windows); ``` ### Per-Call WindowLabel Not Taking Effect[​](#per-call-windowlabel-not-taking-effect "Direct link to Per-Call WindowLabel Not Taking Effect") **Issue:** Using `{ windowLabel: 'popup' }` in execute call still uses the main window. **Why this happens:** The sentinel is required to distinguish options from script arguments. Plain objects are treated as user arguments, not options. **Solutions:** 1. Verify the window exists: `const windows = await browser.tauri.listWindows();` 2. Use `browser.tauri.switchWindow(label)` to change the session default 3. Check that @wdio/tauri-plugin is installed and registered in your Tauri app 4. Use `withExecuteOptions()` wrapper for per-call windowLabel: ``` import { withExecuteOptions } from '@wdio/tauri-service'; const result = await browser.tauri.execute( (tauri) => tauri.core.invoke('get_data'), withExecuteOptions({ windowLabel: 'popup' }) ); ``` ``` // wdio.conf.ts export const config = { capabilities: [{ 'wdio:tauriServiceOptions': { driverProvider: 'embedded', }, }], }; ``` ## Debug Mode[​](#debug-mode "Direct link to Debug Mode") ### Enable Debug Logging[​](#enable-debug-logging "Direct link to Enable Debug Logging") Get more detailed information about what the service is doing: ``` services: [ ['@wdio/tauri-service', { logLevel: 'debug', // Verbose logging commandTimeout: 60000 }] ] ``` ### Verbose Test Output[​](#verbose-test-output "Direct link to Verbose Test Output") ``` npx wdio run wdio.conf.ts --logLevel debug ``` ### Check Service Status[​](#check-service-status "Direct link to Check Service Status") ``` it('should check service', async () => { const service = browser.getService('@wdio/tauri-service'); console.log('Service:', service); }); ``` ## Performance Issues[​](#performance-issues "Direct link to Performance Issues") ### Tests Running Slow[​](#tests-running-slow "Direct link to Tests Running Slow") **Solution 1: Disable Unnecessary Log Capture** ``` services: [ ['@wdio/tauri-service', { captureBackendLogs: false, captureFrontendLogs: false, // Logs add overhead }] ] ``` **Solution 2: Increase Log Level** ``` services: [ ['@wdio/tauri-service', { backendLogLevel: 'warn', // Skip debug/info logs frontendLogLevel: 'warn', }] ] ``` **Solution 3: Run Tests Serially** ``` // wdio.conf.ts export const config = { maxInstances: 1, // Run one test at a time }; ``` ## CI/CD Issues[​](#cicd-issues "Direct link to CI/CD Issues") ### Tests Fail in CI But Pass Locally[​](#tests-fail-in-ci-but-pass-locally "Direct link to Tests Fail in CI But Pass Locally") **Common Causes:** 1. **Missing WebDriver on CI** * Install webkit2gtk-driver on Linux CI * Download MSEdgeDriver on Windows CI 2. **Display Server Missing on Linux CI** * Use Xvfb for headless testing: ``` xvfb-run -a npm run test:e2e ``` 3. **Different Binary on CI** * Ensure build happens before tests: `cargo build --release` * Verify binary path matches CI environment 4. **Environment Variables** * Set `APP_BINARY` or similar if using env-based paths: ``` APP_BINARY="./src-tauri/target/release/my-app" npm run test:e2e ``` ### Example GitHub Actions Setup[​](#example-github-actions-setup "Direct link to Example GitHub Actions Setup") ``` name: E2E Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - uses: dtolnay/rust-toolchain@stable - name: Install webkit2gtk-driver run: sudo apt-get install -y webkit2gtk-driver - name: Install dependencies run: npm install - name: Build Tauri app run: npm run tauri build - name: Run tests with Xvfb run: xvfb-run -a npm run test:e2e ``` ## Getting Help[​](#getting-help "Direct link to Getting Help") If you're still stuck: 1. **Check [Configuration](/docs/desktop-testing/tauri/configuration.md)** for all available options 2. **Review [Usage Examples](/docs/desktop-testing/tauri/usage-examples.md)** for correct patterns 3. **See [Plugin Setup](/docs/desktop-testing/tauri/plugin-setup.md)** for plugin requirements 4. **Check [Platform Support](/docs/desktop-testing/tauri/platform-support.md)** for platform-specific issues 5. **Enable debug logging** to see detailed output 6. **Open a discussion** in the [GitHub Discussions](https://github.com/webdriverio/desktop-mobile/discussions) or [WDIO forum](https://github.com/webdriverio/webdriverio/discussions) --- Source: https://webdriver.io/docs/desktop-testing/dioxus.md # Dioxus [Dioxus](https://dioxuslabs.com/) is a Rust framework for building cross-platform apps from a single codebase. Its desktop apps render in the operating system's native webview (Wry), and WebdriverIO's Dioxus service automates their discovery, launch, and driving on Windows (WebView2), macOS (WKWebView), and Linux (WebKitGTK) so the same test suite works everywhere. The advantages of using WebdriverIO for testing Dioxus applications are: * 🚗 auto-provisioning of the WebDriver layer — the recommended embedded in-process driver needs no external driver binary on any platform * 📦 cross-platform binary detection (Edge WebView2 driver bundled on Windows for the `external` provider) * 🧩 `browser.dioxus.execute()`, mocking and window management, provided by the service via the `wdio-dioxus-bridge` crate * 🔗 deeplink + protocol handler testing * 🪵 forwarding of Rust + frontend logs into the WebdriverIO test reporter ## Getting Started[​](#getting-started "Direct link to Getting Started") To initiate a new WebdriverIO project, run: ``` npm create wdio@latest ./ ``` When the wizard asks what type of testing you'd like to do, select *"Desktop Testing - of Electron, Tauri, Dioxus, or macOS Applications"*, then choose *Dioxus* at the framework prompt. The wizard will then ask which WebDriver provider you want to use (the recommended embedded in-process driver, or the Windows-only external driver) and the path to your built debug binary. The wizard installs the npm packages automatically and prints the required Cargo additions to stdout for you to paste into your `Cargo.toml`. ## Manual Setup[​](#manual-setup "Direct link to Manual Setup") If you already have a WebdriverIO project, install the service: ``` npm install --save-dev @wdio/dioxus-service ``` Testing requires the `wdio-dioxus-bridge` crate — it enables `browser.dioxus.execute()`, mocking, and log capture. Add it to your `Cargo.toml`: ``` [dependencies] wdio-dioxus-bridge = "1" ``` …and install it into your Dioxus desktop config in `src/main.rs`. The `#[cfg(debug_assertions)]` guard keeps the bridge out of release builds: ``` fn main() { let mut config = dioxus::desktop::Config::new(); #[cfg(debug_assertions)] { config = wdio_dioxus_bridge::install(config); } dioxus::LaunchBuilder::desktop() .with_cfg(config) .launch(App); } ``` Build the app for testing (a debug build keeps the bridge active): ``` cargo build ``` Then add the service and capabilities to your config: ``` // wdio.conf.ts export const config: WebdriverIO.Config = { // ... services: [['dioxus', { driverProvider: 'embedded' }]], capabilities: [{ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my-app' } }] } ``` That's it 🎉 Learn more about [configuring the Dioxus Service](/docs/desktop-testing/dioxus/configuration.md), [the bridge setup](/docs/desktop-testing/dioxus/plugin-setup.md), [platform-specific notes](/docs/desktop-testing/dioxus/platform-support.md), and [common usage patterns](/docs/desktop-testing/dioxus/usage-examples.md). --- Source: https://webdriver.io/docs/desktop-testing/dioxus/quick-start.md # Quick Start Get up and running with WebdriverIO and Dioxus E2E testing in minutes. ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") ### Required Software[​](#required-software "Direct link to Required Software") 1. **Node.js 18+** - Download from [nodejs.org](https://nodejs.org) 2. **Rust Toolchain** - Required for building Dioxus apps ``` curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ### Platform-Specific Requirements[​](#platform-specific-requirements "Direct link to Platform-Specific Requirements") #### Windows[​](#windows "Direct link to Windows") * **Microsoft Visual C++ Build Tools** - Download from [Microsoft Visual C++](https://visualstudio.microsoft.com/visual-cpp-build-tools/) * The `'embedded'` provider (recommended) requires no additional setup. * The `'external'` provider requires `wdio-dioxus-driver` and msedgedriver — see [Edge WebDriver (Windows)](/docs/desktop-testing/dioxus/edge-webdriver-windows.md). #### Linux[​](#linux "Direct link to Linux") * **WebKitGTK Development Libraries** - Required to build Dioxus desktop apps: ``` # Debian/Ubuntu sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev # Fedora sudo dnf install -y webkit2gtk4.1-devel gtk3-devel # Arch Linux sudo pacman -S webkit2gtk-4.1 gtk3 ``` The `'embedded'` provider is the only supported provider on Linux in v1. `'external'` is blocked pending an upstream Dioxus PR — see [Platform Support](/docs/desktop-testing/dioxus/platform-support.md). #### macOS[​](#macos "Direct link to macOS") ✅ **Supported** - Use the embedded WebDriver provider (`driverProvider: 'embedded'`, the default) for native macOS testing without external dependencies. `'external'` is not supported on macOS. See [Platform Support](/docs/desktop-testing/dioxus/platform-support.md) for details. ## Setting Up a Dioxus App[​](#setting-up-a-dioxus-app "Direct link to Setting Up a Dioxus App") ### Create a Minimal Dioxus Desktop App[​](#create-a-minimal-dioxus-desktop-app "Direct link to Create a Minimal Dioxus Desktop App") ``` mkdir my-dioxus-app cd my-dioxus-app cargo init --name my_app ``` Edit `Cargo.toml`: ``` [package] name = "my_app" version = "0.1.0" edition = "2021" [dependencies] dioxus = { version = "0.6", features = ["desktop"] } wdio-dioxus-bridge = "1" ``` Edit `src/main.rs`: ``` use dioxus::prelude::*; fn main() { let mut config = dioxus::desktop::Config::new(); #[cfg(debug_assertions)] { config = wdio_dioxus_bridge::install(config); } dioxus::LaunchBuilder::desktop().with_cfg(config).launch(App); } #[component] fn App() -> Element { rsx! { h1 { "Hello, Dioxus!" } } } ``` ## Bridge Setup[​](#bridge-setup "Direct link to Bridge Setup") The `wdio-dioxus-bridge` crate is **required** for testing — it enables `browser.dioxus.execute()`, mocking, and log capture. The `#[cfg(debug_assertions)]` guard ensures the bridge is compiled out of release builds. See [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md) for the full rationale and setup options. ## Building the Dioxus App[​](#building-the-dioxus-app "Direct link to Building the Dioxus App") ``` # Build for testing (debug build, bridge is active) cargo build # Or release build (bridge compiled out, for production) cargo build --release ``` The debug binary is at: * `target/debug/my_app` (Linux/macOS) * `target\debug\my_app.exe` (Windows) ## WebdriverIO Installation[​](#webdriverio-installation "Direct link to WebdriverIO Installation") ### 1. Install WebdriverIO[​](#1-install-webdriverio "Direct link to 1. Install WebdriverIO") ``` npm install --save-dev @wdio/cli @wdio/dioxus-service ``` ### 2. Create Configuration[​](#2-create-configuration "Direct link to 2. Create Configuration") Create `wdio.conf.ts`: ``` export const config = { runner: 'local', specs: ['./test/specs/**/*.spec.ts'], maxInstances: 1, services: [['@wdio/dioxus-service', { driverProvider: 'embedded', // Recommended on all platforms }]], capabilities: [{ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', // Path to debug binary }, }], logLevel: 'info', waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: 'mocha', mochaOpts: { ui: 'bdd', timeout: 60000, }, }; ``` ### 3. Create a Test[​](#3-create-a-test "Direct link to 3. Create a Test") Create `test/specs/example.spec.ts`: ``` describe('My Dioxus App', () => { it('should display hello world', async () => { await browser.pause(500); const heading = await browser.$('h1'); expect(await heading.getText()).toBe('Hello, Dioxus!'); }); it('should execute Dioxus commands', async () => { const mock = await browser.dioxus.mock('get_platform_info'); await mock.mockReturnValue({ platform: 'linux', arch: 'x86_64' }); const result = await browser.dioxus.execute(({ invoke }) => { return invoke('get_platform_info'); }); expect(result).toHaveProperty('platform'); }); it('should mock Dioxus commands', async () => { const mock = await browser.dioxus.mock('get_user'); await mock.mockReturnValue({ id: 1, name: 'Test User' }); const user = await browser.dioxus.execute(({ invoke }) => { return invoke('get_user'); }); expect(user).toEqual({ id: 1, name: 'Test User' }); }); }); ``` ## Running Tests[​](#running-tests "Direct link to Running Tests") ### Run All Tests[​](#run-all-tests "Direct link to Run All Tests") ``` npx wdio run wdio.conf.ts ``` ### Run Specific Test File[​](#run-specific-test-file "Direct link to Run Specific Test File") ``` npx wdio run wdio.conf.ts --spec test/specs/example.spec.ts ``` ### Run with Debug Logging[​](#run-with-debug-logging "Direct link to Run with Debug Logging") ``` npx wdio run wdio.conf.ts --logLevel debug ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### "Bridge not available" or execute returns undefined[​](#bridge-not-available-or-execute-returns-undefined "Direct link to \"Bridge not available\" or execute returns undefined") The `wdio-dioxus-bridge` crate is not wired into your app. Make sure: 1. Add to `[dependencies]` in `Cargo.toml`: ``` wdio-dioxus-bridge = "1" ``` 2. Call `wdio_dioxus_bridge::install(config)` in `main.rs` inside a `#[cfg(debug_assertions)]` block. 3. Build in debug mode (`cargo build`, not `cargo build --release`). ### "Application not found at path"[​](#application-not-found-at-path "Direct link to \"Application not found at path\"") The `appBinaryPath` or `dioxus:options.application` is wrong. Verify: 1. You built the app: `cargo build` 2. The path exists: `./target/debug/my_app` 3. Update the path in `wdio.conf.ts` if needed ### Tests timeout on Windows (`'external'` provider)[​](#tests-timeout-on-windows-external-provider "Direct link to tests-timeout-on-windows-external-provider") Edge WebDriver version mismatch. See [Edge WebDriver (Windows)](/docs/desktop-testing/dioxus/edge-webdriver-windows.md). ### Linux: "external provider not supported"[​](#linux-external-provider-not-supported "Direct link to Linux: \"external provider not supported\"") `'external'` is blocked on Linux in v1. Use `driverProvider: 'embedded'` instead. ## Next Steps[​](#next-steps "Direct link to Next Steps") 1. **Add more tests** - See [Usage Examples](/docs/desktop-testing/dioxus/usage-examples.md) for patterns 2. **Advanced features** - Read about [Mocking](/docs/desktop-testing/dioxus/api.md#mock-functions) and [Log Forwarding](/docs/desktop-testing/dioxus/log-forwarding.md) 3. **Configure the service** - See [Configuration](/docs/desktop-testing/dioxus/configuration.md) for all options 4. **Debug issues** - Check [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md) ## Common Patterns[​](#common-patterns "Direct link to Common Patterns") ### Test Custom Dioxus Commands[​](#test-custom-dioxus-commands "Direct link to Test Custom Dioxus Commands") ``` it('should call custom commands', async () => { const result = await browser.dioxus.execute(({ invoke }) => { return invoke('my_custom_command', { param: 'value' }); }); expect(result).toBeDefined(); }); ``` ### Capture Logs[​](#capture-logs "Direct link to Capture Logs") Enable log capture in `wdio.conf.ts`: ``` services: [['@wdio/dioxus-service', { captureBackendLogs: true, captureFrontendLogs: true, backendLogLevel: 'debug', frontendLogLevel: 'debug', }]], ``` ### Multiremote Testing[​](#multiremote-testing "Direct link to Multiremote Testing") Run multiple instances of your app: ``` capabilities: [ { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, }, { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, }, ], ``` ### CI/CD Integration[​](#cicd-integration "Direct link to CI/CD Integration") Example GitHub Actions workflow: ``` name: E2E Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest # or windows-latest / macos-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' - uses: dtolnay/rust-toolchain@stable - name: Install Linux dependencies if: runner.os == 'Linux' run: sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev - name: Install dependencies run: npm install - name: Build Dioxus app run: cargo build - name: Run tests (Linux needs a virtual display for desktop apps) if: runner.os == 'Linux' run: xvfb-run -a npm run test:e2e - name: Run tests if: runner.os != 'Linux' run: npm run test:e2e ``` ## See Also[​](#see-also "Direct link to See Also") * [Configuration Reference](/docs/desktop-testing/dioxus/configuration.md) * [API Reference](/docs/desktop-testing/dioxus/api.md) * [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md) * [Platform Support](/docs/desktop-testing/dioxus/platform-support.md) * [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md) * [WebdriverIO Documentation](https://webdriver.io/docs) * [Dioxus Documentation](https://dioxuslabs.com/learn/0.6/) --- Source: https://webdriver.io/docs/desktop-testing/dioxus/configuration.md # Configuration Complete guide to configuring @wdio/dioxus-service in your WebdriverIO setup. ## Service Configuration[​](#service-configuration "Direct link to Service Configuration") Add the Dioxus service to your `wdio.conf.ts`: ``` export const config = { services: [ ['@wdio/dioxus-service', { // Service options go here driverProvider: 'embedded', captureBackendLogs: true, captureFrontendLogs: true, }] ], // ... rest of config }; ``` ## Service Options[​](#service-options "Direct link to Service Options") ### `driverProvider`[​](#driverprovider "Direct link to driverprovider") * Type `'external' | 'embedded'` * Default `'embedded'` * Required `No` Select which driver provider to use for WebDriver communication. * `'embedded'`: Use the embedded WebDriver server wired in via `wdio-dioxus-bridge::install()`. No external driver needed. Works on all three platforms. * `'external'`: Use `wdio-dioxus-driver` + msedgedriver (Windows only in v1). Linux is blocked pending an upstream Dioxus PR; macOS is not supported. **Platform × Provider matrix:** | Platform | `'embedded'` | `'external'` | | -------- | ------------ | ---------------- | | Windows | ✅ Yes | ✅ Yes | | Linux | ✅ Yes | ❌ Blocked in v1 | | macOS | ✅ Yes | ❌ Not supported | **Example:** ``` driverProvider: 'embedded' // Recommended everywhere driverProvider: 'external' // Windows only in v1 ``` ### `appBinaryPath`[​](#appbinarypath "Direct link to appbinarypath") * Type `string` * Default `Auto-detected from dioxus:options.application capability if not provided.` * Required `No` Path to the compiled Dioxus application binary. **Example:** ``` appBinaryPath: './target/debug/my_app', // debug build (bridge active) appBinaryPath: './target/release/my_app', // release build (bridge inactive) ``` **Note:** For testing, always use a debug build (`cargo build` without `--release`) so the bridge is compiled in. ### `appArgs`[​](#appargs "Direct link to appargs") * Type `string[]` * Default `[]` * Required `No` Command-line arguments to pass to the Dioxus application when launching. Each array element is a separate argument — no shell parsing is applied. **Example:** ``` appArgs: ['--debug', '--log-level', 'debug'] appArgs: ['--window-size=1920,1080'] ``` ### `autoInstallDioxusDriver`[​](#autoinstalldioxusdriver "Direct link to autoinstalldioxusdriver") * Type `boolean` * Default `false` * Required `No` Automatically install `wdio-dioxus-driver` if not found in PATH. Only relevant when `driverProvider: 'external'`. Requires Rust toolchain (`cargo`). **Example:** ``` autoInstallDioxusDriver: true ``` ### `autoDownloadEdgeDriver`[​](#autodownloadedgedriver "Direct link to autodownloadedgedriver") * Type `boolean` * Default `true` * Required `No` Automatically download MSEdgeDriver on Windows if a version mismatch is detected. Only relevant when `driverProvider: 'external'` on Windows. **Example:** ``` autoDownloadEdgeDriver: true // Windows + external provider only ``` **Note:** Ignored on Linux and macOS. See [Edge WebDriver (Windows)](/docs/desktop-testing/dioxus/edge-webdriver-windows.md). ### `dioxusDriverPort`[​](#dioxusdriverport "Direct link to dioxusdriverport") * Type `number` * Default `4444` * Required `No` Port for `wdio-dioxus-driver` to listen on. Only used when `driverProvider: 'external'`. **Example:** ``` dioxusDriverPort: 4444 ``` ### `dioxusDriverPath`[​](#dioxusdriverpath "Direct link to dioxusdriverpath") * Type `string` * Default `Use wdio-dioxus-driver from PATH.` * Required `No` Path to the `wdio-dioxus-driver` executable if not in PATH. Only used when `driverProvider: 'external'`. **Example:** ``` dioxusDriverPath: '/usr/local/bin/wdio-dioxus-driver' dioxusDriverPath: 'C:\\tools\\wdio-dioxus-driver.exe' ``` ### `embeddedPort`[​](#embeddedport "Direct link to embeddedport") * Type `number` * Default `4445` * Required `No` Port for the embedded WebDriver server. Only used when `driverProvider: 'embedded'`. Each worker instance gets a unique port (basePort + workerIndex). **Example:** ``` embeddedPort: 4445 ``` ### `statusPollTimeout`[​](#statuspolltimeout "Direct link to statuspolltimeout") * Type `number` * Default `2000` * Required `No` Timeout in milliseconds for the `/status` endpoint poll during embedded WebDriver server startup. Increase this in slow CI environments where a healthy-but-busy server may miss the default deadline. **Example:** ``` statusPollTimeout: 5000 ``` **Note:** Only applies when `driverProvider: 'embedded'`. ### `startTimeout`[​](#starttimeout "Direct link to starttimeout") * Type `number` * Default `60000 for the 'embedded' provider; 30000 for 'external'.` * Required `No` Timeout in milliseconds for the Dioxus app to start and become ready. **Example:** ``` startTimeout: 60000 // 60 seconds ``` ### `windowLabel`[​](#windowlabel "Direct link to windowlabel") * Type `string` * Default `'main'` * Required `No` The default window label to target for Dioxus operations. Controls which webview window `browser.dioxus.execute()` and other Dioxus-specific operations target by default. **Example:** ``` windowLabel: 'settings' // Target the settings window by default ``` **Note:** Override at runtime with `browser.dioxus.switchWindow(label)`. ### `captureBackendLogs`[​](#capturebackendlogs "Direct link to capturebackendlogs") * Type `boolean` * Default `false` * Required `No` Capture logs from the Dioxus backend (Rust code) and forward them to WebdriverIO's logger. **Example:** ``` captureBackendLogs: true ``` **Note:** See [Log Forwarding](/docs/desktop-testing/dioxus/log-forwarding.md). ### `captureFrontendLogs`[​](#capturefrontendlogs "Direct link to capturefrontendlogs") * Type `boolean` * Default `false` * Required `No` Capture console logs from the frontend (JavaScript/TypeScript in the webview). **Example:** ``` captureFrontendLogs: true ``` **Note:** See [Log Forwarding](/docs/desktop-testing/dioxus/log-forwarding.md). ### `backendLogLevel`[​](#backendloglevel "Direct link to backendloglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` * Required `No` Minimum log level to capture from the Rust backend. Logs below this level are ignored. **Example:** ``` backendLogLevel: 'debug' // Capture debug and above ``` **Note:** Only has effect if `captureBackendLogs: true`. ### `frontendLogLevel`[​](#frontendloglevel "Direct link to frontendloglevel") * Type `'trace' | 'debug' | 'info' | 'warn' | 'error'` * Default `'info'` * Required `No` Minimum log level to capture from the frontend webview. Logs below this level are ignored. **Example:** ``` frontendLogLevel: 'debug' ``` **Note:** Only has effect if `captureFrontendLogs: true`. ### `env`[​](#env "Direct link to env") * Type `Record` * Default `{}` * Required `No` Additional environment variables to pass to the Dioxus application process. **Example:** ``` env: { RUST_LOG: 'debug', MY_APP_ENV: 'test', } ``` ### `mode`[​](#mode "Direct link to mode") * Type `'native' | 'browser'` * Default `'native'` * Required `No` Controls how the service connects to your application. * `'native'` (default) — launches your compiled Dioxus binary via the configured driver provider. * `'browser'` — skips all driver and binary setup; sets `browserName = 'chrome'`, navigates to `devServerUrl`, and intercepts the invoke API so Dioxus commands can be mocked without a running Rust backend. **Example:** ``` mode: 'browser' ``` > All capabilities in a session must use the same mode. Mixing `'native'` and `'browser'` across capabilities throws a `SevereServiceError` at startup. See [Browser Mode](/docs/desktop-testing/dioxus/browser-mode.md) for setup, mocking, and limitations. ### `devServerUrl`[​](#devserverurl "Direct link to devserverurl") * Type `string` * Default `undefined` * Required `Yes in browser mode` URL of the dev server to navigate to when `mode: 'browser'` is set. Validated with `new URL()` at startup. **Example:** ``` devServerUrl: 'http://localhost:8080' ``` **Note:** Only used when `mode: 'browser'`. Has no effect in native mode. See [Browser Mode](/docs/desktop-testing/dioxus/browser-mode.md). ### `clearMocks`[​](#clearmocks "Direct link to clearmocks") * Type `boolean` * Default `false` * Required `No` If `true`, all mock call history is cleared before each test. Equivalent to calling `browser.dioxus.clearAllMocks()` in a `beforeEach`. ### `clearMocksPrefix`[​](#clearmocksprefix "Direct link to clearmocksprefix") * Type `string` * Default `undefined` * Required `No` If set, only mocks whose command name starts with this prefix are cleared. Only used when `clearMocks: true`. ### `resetMocks`[​](#resetmocks "Direct link to resetmocks") * Type `boolean` * Default `false` * Required `No` If `true`, all mocks are reset (implementation + history) before each test. ### `resetMocksPrefix`[​](#resetmocksprefix "Direct link to resetmocksprefix") * Type `string` * Default `undefined` * Required `No` If set, only mocks whose command name starts with this prefix are reset. Only used when `resetMocks: true`. ### `restoreMocks`[​](#restoremocks "Direct link to restoremocks") * Type `boolean` * Default `false` * Required `No` If `true`, all mocks are restored to their original implementations before each test. ### `restoreMocksPrefix`[​](#restoremocksprefix "Direct link to restoremocksprefix") * Type `string` * Default `undefined` * Required `No` If set, only mocks whose command name starts with this prefix are restored. Only used when `restoreMocks: true`. ## Capabilities Configuration[​](#capabilities-configuration "Direct link to Capabilities Configuration") Configure Dioxus-specific capabilities in your `capabilities` array: ### Basic Configuration[​](#basic-configuration "Direct link to Basic Configuration") ``` capabilities: [{ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app' } }] ``` ### Full Capability Configuration[​](#full-capability-configuration "Direct link to Full Capability Configuration") ``` capabilities: [{ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', args: ['--debug'], webviewOptions: { width: 1280, height: 800, }, }, 'wdio:dioxusServiceOptions': { windowLabel: 'main', captureBackendLogs: true, }, }] ``` ### `dioxus:options` Fields[​](#dioxusoptions-fields "Direct link to dioxusoptions-fields") | Field | Type | Required | Description | | ----------------------- | --------- | -------- | ------------------------------- | | `application` | string | Yes | Path to the Dioxus app binary | | `args` | string\[] | No | Arguments passed to the app | | `webviewOptions.width` | number | No | Initial window width in pixels | | `webviewOptions.height` | number | No | Initial window height in pixels | ### Multiremote Configuration[​](#multiremote-configuration "Direct link to Multiremote Configuration") ``` capabilities: { app1: { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app' } }, app2: { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app' } } } ``` ## Complete Configuration Example[​](#complete-configuration-example "Direct link to Complete Configuration Example") ``` // wdio.conf.ts export const config = { runner: 'local', specs: ['./test/specs/**/*.spec.ts'], maxInstances: 1, services: [ ['@wdio/dioxus-service', { driverProvider: 'embedded', appBinaryPath: './target/debug/my_app', appArgs: [], embeddedPort: 4445, startTimeout: 60000, statusPollTimeout: 2000, captureBackendLogs: true, captureFrontendLogs: true, backendLogLevel: 'debug', frontendLogLevel: 'debug', windowLabel: 'main', clearMocks: false, resetMocks: false, restoreMocks: false, }] ], capabilities: [{ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, }], logLevel: 'info', bail: 0, waitforTimeout: 10000, connectionRetryTimeout: 90000, connectionRetryCount: 3, framework: 'mocha', mochaOpts: { ui: 'bdd', timeout: 60000, }, reporters: ['spec'], }; ``` ## Platform-Specific Configuration[​](#platform-specific-configuration "Direct link to Platform-Specific Configuration") ### Windows (`'embedded'` — recommended)[​](#windows-embedded--recommended "Direct link to windows-embedded--recommended") ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'embedded', appBinaryPath: './target/debug/my_app.exe', }] ] ``` ### Windows (`'external'`)[​](#windows-external "Direct link to windows-external") ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'external', autoInstallDioxusDriver: true, autoDownloadEdgeDriver: true, appBinaryPath: './target/debug/my_app.exe', }] ] ``` ### Linux (embedded only)[​](#linux-embedded-only "Direct link to Linux (embedded only)") ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'embedded', // Only supported option on Linux appBinaryPath: './target/debug/my_app', }] ] ``` ### macOS (embedded only)[​](#macos-embedded-only "Direct link to macOS (embedded only)") ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'embedded', // Only supported option on macOS appBinaryPath: './target/debug/my_app', }] ] ``` ## Finding Your Binary Path[​](#finding-your-binary-path "Direct link to Finding Your Binary Path") ### Debug Build (for testing)[​](#debug-build-for-testing "Direct link to Debug Build (for testing)") ``` cargo build ``` Binary locations: * Windows: `target\debug\my_app.exe` * Linux/macOS: `target/debug/my_app` ### Release Build (for production — bridge compiled out)[​](#release-build-for-production--bridge-compiled-out "Direct link to Release Build (for production — bridge compiled out)") ``` cargo build --release ``` Binary locations: * Windows: `target\release\my_app.exe` * Linux/macOS: `target/release/my_app` **Always use a debug build for testing** so the bridge code is present. ## See Also[​](#see-also "Direct link to See Also") * [Quick Start](/docs/desktop-testing/dioxus/quick-start.md) for getting started * [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md) for bridge configuration * [API Reference](/docs/desktop-testing/dioxus/api.md) for available functions * [Log Forwarding](/docs/desktop-testing/dioxus/log-forwarding.md) for logging configuration * [Platform Support](/docs/desktop-testing/dioxus/platform-support.md) for per-platform details --- Source: https://webdriver.io/docs/desktop-testing/dioxus/api.md # API Reference Complete API reference for @wdio/dioxus-service. ## browser.dioxus API[​](#browserdioxus-api "Direct link to browser.dioxus API") The following methods are available on the `browser.dioxus` object when connected to a Dioxus app. ### `browser.dioxus.execute(script, ...args)`[​](#browserdioxusexecutescript-args "Direct link to browserdioxusexecutescript-args") Execute JavaScript code in the Dioxus webview context with access to Dioxus IPC APIs. Requires `wdio-dioxus-bridge` to be installed and configured in your app. **Parameters:** * `script` (Function | string) - JavaScript code to execute. If a function, receives a `DioxusAPIs` object (`dx`) as the first parameter * `...args` (any\[]) - Additional arguments passed to the script **Returns:** `Promise\` **`DioxusAPIs` (`dx`) object:** ``` interface DioxusAPIs { invoke: (command: string, args?: unknown) => Promise; log?: { trace: (msg: string) => void; debug: (msg: string) => void; info: (msg: string) => void; warn: (msg: string) => void; error: (msg: string) => void; }; } ``` **Example:** ``` // Execute with destructured DioxusAPIs const result = await browser.dioxus.execute(({ invoke }) => { return invoke('get_platform_info'); }); // Execute with full DioxusAPIs object const greeting = await browser.dioxus.execute(async (dx) => { return dx.invoke('greet', { name: 'World' }); }); // Execute with arguments const result = await browser.dioxus.execute( (dx, name) => dx.invoke('greet', { name }), 'World' ); // Execute string of code const href = await browser.dioxus.execute('window.location.href'); ``` **Note:** Requires `wdio-dioxus-bridge` to be installed. See [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md). ### `browser.dioxus.mock(command)`[​](#browserdioxusmockcommand "Direct link to browserdioxusmockcommand") Mock a specific Dioxus backend command. Returns a `DioxusMock` object for configuring the mock behavior. **Parameters:** * `command` (string) - Name of the Dioxus command to mock (must match what your app passes to `invoke()`) **Returns:** `Promise\` **Example:** ``` const mock = await browser.dioxus.mock('read_file'); await mock.mockReturnValue('mocked file content'); // Now calling invoke('read_file', ...) returns 'mocked file content' const content = await browser.dioxus.execute(({ invoke }) => invoke('read_file')); expect(content).toBe('mocked file content'); ``` ### `browser.dioxus.isMockFunction(fn)`[​](#browserdioxusismockfunctionfn "Direct link to browserdioxusismockfunctionfn") Check if a value is a Dioxus mock function. This is a TypeScript type guard. **Parameters:** * `fn` (unknown) - Value to check **Returns:** `boolean` (type narrows to `DioxusMockInstance` when true) **Example:** ``` const mock = await browser.dioxus.mock('clipboard_read'); if (browser.dioxus.isMockFunction(mock)) { // TypeScript knows mock is DioxusMockInstance here expect(mock.mock.calls).toHaveLength(1); } ``` ### `browser.dioxus.clearAllMocks(commandPrefix?)`[​](#browserdioxusclearallmockscommandprefix "Direct link to browserdioxusclearallmockscommandprefix") Clear all mock call history and reset results, but keep the mock implementations in place. **Parameters:** * `commandPrefix` (string, optional) - If provided, only mocks with command names starting with this prefix will be cleared **Returns:** `Promise\` **Example:** ``` // Clear all mocks await browser.dioxus.clearAllMocks(); // Clear only clipboard-related mocks await browser.dioxus.clearAllMocks('clipboard'); ``` ### `browser.dioxus.resetAllMocks(commandPrefix?)`[​](#browserdioxusresetallmockscommandprefix "Direct link to browserdioxusresetallmockscommandprefix") Reset all mocks to their initial state (clears implementations and call history). **Parameters:** * `commandPrefix` (string, optional) - If provided, only mocks with matching prefix are reset **Returns:** `Promise\` ### `browser.dioxus.restoreAllMocks(commandPrefix?)`[​](#browserdioxusrestoreallmockscommandprefix "Direct link to browserdioxusrestoreallmockscommandprefix") Remove all mocks and restore original command implementations. **Parameters:** * `commandPrefix` (string, optional) - If provided, only mocks with matching prefix are restored **Returns:** `Promise\` **Example:** ``` await browser.dioxus.restoreAllMocks(); // Commands now call the real Dioxus backend again ``` ### `browser.dioxus.switchWindow(label)`[​](#browserdioxusswitchwindowlabel "Direct link to browserdioxusswitchwindowlabel") Switch the active Dioxus window for subsequent operations. Changes the window that `browser.dioxus.execute()` and other Dioxus-specific operations target. **Parameters:** * `label` (string) - The window label to switch to (e.g., `'main'`, `'settings'`) **Returns:** `Promise\` **Example:** ``` // Switch to the settings window await browser.dioxus.switchWindow('settings'); // Now executes in the settings window context const data = await browser.dioxus.execute(({ invoke }) => invoke('get_settings')); // Switch back to main window await browser.dioxus.switchWindow('main'); ``` **Note:** The window label must exist in your Dioxus app. Use `browser.dioxus.listWindows()` to get available labels. ### `browser.dioxus.listWindows()`[​](#browserdioxuslistwindows "Direct link to browserdioxuslistwindows") Get a list of all available Dioxus window labels in the application. **Returns:** `Promise\` **Example:** ``` const windows = await browser.dioxus.listWindows(); console.log(windows); // ['main', 'settings', 'dialog'] ``` ### `browser.dioxus.triggerDeeplink(url)`[​](#browserdioxustriggerdeeplinkurl "Direct link to browserdioxustriggerdeeplinkurl") Trigger a deeplink to the Dioxus application for testing protocol handlers. Uses platform-specific commands (`open` on macOS, `xdg-open` on Linux, `cmd /c start` on Windows). **Parameters:** * `url` (string) - The deeplink URL to trigger (e.g., `'myapp://open?file=test.txt'`) **Returns:** `Promise\` **Example:** ``` await browser.dioxus.triggerDeeplink('myapp://open?file=test.txt'); await browser.waitUntil(async () => { const openedFile = await browser.dioxus.execute(() => { return globalThis.lastOpenedFile; }); return openedFile === 'test.txt'; }); ``` See [Deeplink Testing](/docs/desktop-testing/dioxus/deeplink-testing.md) for the full usage guide. *** > **Note:** `emitEvent` is deferred to v1.1. ## DioxusMock Interface[​](#dioxusmock-interface "Direct link to DioxusMock Interface") When you call `browser.dioxus.mock(command)`, you receive a `DioxusMock` object with these methods: ### `mockImplementation(fn)`[​](#mockimplementationfn "Direct link to mockimplementationfn") Set a custom implementation function for the mock. **Returns:** `Promise\` **Example:** ``` const mock = await browser.dioxus.mock('calculate'); await mock.mockImplementation(async (args) => args.x + args.y); const result = await browser.dioxus.execute(({ invoke }) => invoke('calculate', { x: 5, y: 3 })); // result === 8 ``` ### `mockImplementationOnce(fn)`[​](#mockimplementationoncefn "Direct link to mockimplementationoncefn") Set a custom implementation for the next call only. **Returns:** `Promise\` ### `mockReturnValue(value)`[​](#mockreturnvaluevalue "Direct link to mockreturnvaluevalue") Set the mock to always return a specific value. **Returns:** `Promise\` **Example:** ``` const mock = await browser.dioxus.mock('get_user'); await mock.mockReturnValue({ id: 1, name: 'John' }); ``` ### `mockReturnValueOnce(value)`[​](#mockreturnvalueoncevalue "Direct link to mockreturnvalueoncevalue") Set the mock to return a specific value for the next call only. **Returns:** `Promise\` **Example:** ``` const mock = await browser.dioxus.mock('counter'); await mock.mockReturnValueOnce(1); await mock.mockReturnValueOnce(2); await mock.mockReturnValue(3); // default for subsequent calls ``` ### `mockResolvedValue(value)`[​](#mockresolvedvaluevalue "Direct link to mockresolvedvaluevalue") Set the mock to return a promise that resolves to the given value. **Returns:** `Promise\` ### `mockResolvedValueOnce(value)`[​](#mockresolvedvalueoncevalue "Direct link to mockresolvedvalueoncevalue") Set the mock to resolve to a value for the next call only. **Returns:** `Promise\` ### `mockRejectedValue(error)`[​](#mockrejectedvalueerror "Direct link to mockrejectedvalueerror") Set the mock to return a promise that rejects with an error. **Returns:** `Promise\` **Example:** ``` const mock = await browser.dioxus.mock('risky_operation'); await mock.mockRejectedValue(new Error('Operation failed')); ``` ### `mockRejectedValueOnce(error)`[​](#mockrejectedvalueonceerror "Direct link to mockrejectedvalueonceerror") Set the mock to reject for the next call only. **Returns:** `Promise\` ### `mockClear()`[​](#mockclear "Direct link to mockclear") Clear the call history of this mock without resetting its implementation. **Returns:** `Promise\` ### `mockReset()`[​](#mockreset "Direct link to mockreset") Reset the mock to its initial state (clears both implementation and call history). **Returns:** `Promise\` ### `mockRestore()`[​](#mockrestore "Direct link to mockrestore") Remove this mock and restore the original command implementation. **Returns:** `Promise\` ### `mockReturnThis()`[​](#mockreturnthis "Direct link to mockreturnthis") Set the mock to return `this` when called. **Returns:** `Promise\` ### `mockName(name)` / `getMockName()`[​](#mocknamename--getmockname "Direct link to mocknamename--getmockname") Set or get a display name for the mock (useful for debugging). ### `getMockImplementation()`[​](#getmockimplementation "Direct link to getmockimplementation") Get the current implementation function of the mock. ### `update()`[​](#update "Direct link to update") Sync mock call data from the inner mock (app context) to the outer mock (test process). **Returns:** `Promise\` ### `withImplementation(implFn, callbackFn)`[​](#withimplementationimplfn-callbackfn "Direct link to withimplementationimplfn-callbackfn") Temporarily use a different implementation for the duration of a callback. **Example:** ``` const mock = await browser.dioxus.mock('my_command'); await mock.mockReturnValue('default'); await mock.withImplementation( () => 'temporary', async () => { const result = await browser.dioxus.execute(({ invoke }) => invoke('my_command')); console.log(result); // 'temporary' } ); const result = await browser.dioxus.execute(({ invoke }) => invoke('my_command')); console.log(result); // 'default' ``` ### Mock Properties[​](#mock-properties "Direct link to Mock Properties") * `mock.mock.calls` - Array of call arguments * `mock.mock.results` - Array of call results * `__isDioxusMock` - Boolean flag identifying Dioxus mocks ## Package Exports[​](#package-exports "Direct link to Package Exports") ### `startWdioSession(capabilities, globalOptions?)`[​](#startwdiosessioncapabilities-globaloptions "Direct link to startwdiosessioncapabilities-globaloptions") Initialize the Dioxus service in standalone mode. Use this when you want to manage the session manually outside of WebdriverIO's lifecycle. **Parameters:** * `capabilities` (Capabilities) - WebdriverIO capabilities with Dioxus options * `globalOptions?` (DioxusServiceGlobalOptions) - Global service options **Returns:** `Promise\` **Example:** ``` import { startWdioSession } from '@wdio/dioxus-service'; const browser = await startWdioSession({ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app' } }); // Use browser... await browser.deleteSession(); ``` ## Exported Types[​](#exported-types "Direct link to Exported Types") ### `DioxusCapabilities`[​](#dioxuscapabilities "Direct link to dioxuscapabilities") ``` interface DioxusCapabilities extends WebdriverIO.Capabilities { browserName?: 'dioxus'; 'dioxus:options'?: { application: string; args?: string[]; webviewOptions?: { width?: number; height?: number; }; }; 'wdio:dioxusServiceOptions'?: DioxusServiceOptions; } ``` ### `DioxusServiceOptions`[​](#dioxusserviceoptions "Direct link to dioxusserviceoptions") ``` interface DioxusServiceOptions { mode?: 'native' | 'browser'; devServerUrl?: string; driverProvider?: 'external' | 'embedded'; dioxusDriverPort?: number; dioxusDriverPath?: string; embeddedPort?: number; appBinaryPath?: string; appArgs?: string[]; env?: Record; autoInstallDioxusDriver?: boolean; autoDownloadEdgeDriver?: boolean; windowLabel?: string; captureBackendLogs?: boolean; captureFrontendLogs?: boolean; backendLogLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; frontendLogLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; startTimeout?: number; statusPollTimeout?: number; clearMocks?: boolean; clearMocksPrefix?: string; resetMocks?: boolean; resetMocksPrefix?: string; restoreMocks?: boolean; restoreMocksPrefix?: string; } ``` ### `DioxusResult\`[​](#dioxusresultt "Direct link to dioxusresultt") Uses the standard Result pattern: ``` type DioxusResult = { ok: true; value: T } | { ok: false; error: string }; // Usage if (result.ok) { console.log(result.value); } else { console.error(result.error); } ``` ## Notes[​](#notes "Direct link to Notes") * All `browser.dioxus.*` methods require `wdio-dioxus-bridge` to be installed in the Dioxus app. See [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md). * Mocking requires the bridge for invoke interception to work. * `triggerDeeplink` requires your app to register a custom URL scheme. * `emitEvent` is deferred to v1.1. * For detailed configuration examples, see [Configuration](/docs/desktop-testing/dioxus/configuration.md). --- Source: https://webdriver.io/docs/desktop-testing/dioxus/plugin-setup.md # Bridge Setup ## Overview[​](#overview "Direct link to Overview") The `wdio-dioxus-bridge` is a **required** Rust crate that enables WebdriverIO testing of Dioxus desktop applications. It provides: * **Execute API** - Run JavaScript code from tests with access to Dioxus IPC (`invoke`) * **Mocking Support** - Mock Dioxus backend commands for isolated testing * **Log Forwarding** - Capture console logs from both the frontend webview and Rust backend * **Invoke Interception** - Enable mocking without modifying backend command handlers Unlike Tauri's plugin system, Dioxus has no plugin-trait interface. The bridge is therefore a plain Rust crate (not a plugin) that wires itself into the Dioxus `desktop::Config` via a single `install()` call. It uses a `wdio://` custom protocol registered on the webview to communicate with the WDIO service process. No capability permission system is involved — the bridge communicates through its own protocol channel, not through Dioxus's IPC machinery. ## What the Bridge Provides[​](#what-the-bridge-provides "Direct link to What the Bridge Provides") | Feature | Available | | ------------------------------------------------- | ----------------------------------------- | | `browser.dioxus.execute()` | ✅ Yes | | `browser.dioxus.mock()` and all mock operations | ✅ Yes | | `browser.dioxus.listWindows()` / `switchWindow()` | ✅ Yes | | Backend log capture (`captureBackendLogs`) | ✅ Yes | | Frontend log capture (`captureFrontendLogs`) | ✅ Yes | | Embedded WebDriver server | ✅ Yes (wired in automatically) | | `browser.dioxus.triggerDeeplink()` | ✅ Yes (platform-level; no bridge needed) | ## Installation[​](#installation "Direct link to Installation") ### Step 1: Add the Bridge Crate[​](#step-1-add-the-bridge-crate "Direct link to Step 1: Add the Bridge Crate") Add `wdio-dioxus-bridge` to your `Cargo.toml`. The recommended placement is under `[dependencies]` (not `[dev-dependencies]`) because the `#[cfg(debug_assertions)]` guard in your Rust code controls when the bridge code is actually compiled and linked: ``` [package] name = "my_app" version = "0.1.0" edition = "2021" [dependencies] dioxus = { version = "0.6", features = ["desktop"] } wdio-dioxus-bridge = "1" ``` > **Why `[dependencies]` and not `[dev-dependencies]`?** > > `[dev-dependencies]` are only available in test builds (`cargo test`), not in normal `cargo build` invocations. Since the bridge must be present for `cargo build` to compile the `#[cfg(debug_assertions)]`-guarded block, place it in `[dependencies]`. The guard ensures the bridge code is dead-code-eliminated from release builds (`cargo build --release`) automatically. ### Step 2: Wire the Bridge in `main.rs`[​](#step-2-wire-the-bridge-in-mainrs "Direct link to step-2-wire-the-bridge-in-mainrs") Call `wdio_dioxus_bridge::install(config)` inside a `#[cfg(debug_assertions)]` block: ``` use dioxus::prelude::*; fn main() { let mut config = dioxus::desktop::Config::new(); #[cfg(debug_assertions)] { config = wdio_dioxus_bridge::install(config); } dioxus::LaunchBuilder::desktop() .with_cfg(config) .launch(App); } #[component] fn App() -> Element { rsx! { h1 { "Hello, Dioxus!" } } } ``` The `#[cfg(debug_assertions)]` guard means: * **Debug builds** (`cargo build`): bridge is active, WDIO can connect * **Release builds** (`cargo build --release`): bridge code is not compiled, no test plumbing ships to users ### Step 3: Build in Debug Mode[​](#step-3-build-in-debug-mode "Direct link to Step 3: Build in Debug Mode") For testing, always use a debug build: ``` cargo build # Binary: target/debug/my_app (or my_app.exe on Windows) ``` The service's `appBinaryPath` or `dioxus:options.application` should point to the debug binary. ### Step 4: Verify[​](#step-4-verify "Direct link to Step 4: Verify") Build should complete without errors. The bridge registers itself on the Dioxus `Config` and the embedded WebDriver server is wired automatically — no further Rust code is needed. ## What the Bridge Does Internally[​](#what-the-bridge-does-internally "Direct link to What the Bridge Does Internally") When `wdio_dioxus_bridge::install(config)` is called: 1. **Checks `DIOXUS_WEBVIEW_AUTOMATION`** via `wdio_dioxus_bridge::automation::is_requested()`. If the environment variable is not set, the bridge is a no-op. 2. **Registers a `wdio://` custom protocol** on the webview. This protocol is the IPC channel between the WDIO service process and the app's webview. 3. **Wires the embedded WebDriver server** (`wdio-dioxus-embedded-driver`) that listens on the port specified by `DIOXUS_WEBVIEW_AUTOMATION_PORT` (set by the service). 4. **Injects the guest-js bundle** into the webview. This bundle patches the invoke API for mock interception and sets up console log forwarding. 5. **Starts the log forwarder** that reads Rust `log` crate output and forwards it to the WDIO log capture pipeline. This is controlled entirely by environment variables set by `@wdio/dioxus-service` when it launches the app binary. In a normal app run (not driven by WDIO), the bridge is loaded but takes no action. ## `automation::is_requested()`[​](#automationis_requested "Direct link to automationis_requested") You can use `wdio_dioxus_bridge::automation::is_requested()` in your app code to check whether the app is running under WDIO automation: ``` fn main() { let mut config = dioxus::desktop::Config::new(); #[cfg(debug_assertions)] { if wdio_dioxus_bridge::automation::is_requested() { config = wdio_dioxus_bridge::install(config); } } dioxus::LaunchBuilder::desktop().with_cfg(config).launch(App); } ``` `is_requested()` returns `true` when `DIOXUS_WEBVIEW_AUTOMATION=true` is set in the process environment. `@wdio/dioxus-service` sets this variable when launching your app. Calling `install(config)` without checking this first is also safe — the function checks internally and short-circuits. ## Production Considerations[​](#production-considerations "Direct link to Production Considerations") The `#[cfg(debug_assertions)]` guard is the canonical way to ensure the bridge never ships in production: ``` fn main() { let mut config = dioxus::desktop::Config::new(); // This entire block is removed by the compiler in release builds. #[cfg(debug_assertions)] { config = wdio_dioxus_bridge::install(config); } dioxus::LaunchBuilder::desktop().with_cfg(config).launch(App); } ``` When you build with `cargo build --release`, the compiler strips the bridge entirely. No test plumbing is present in the binary that ships to users. If you want additional isolation, you can use a Cargo feature flag: ``` [features] wdio = ["dep:wdio-dioxus-bridge"] [dependencies] wdio-dioxus-bridge = { version = "1", optional = true } ``` ``` fn main() { let mut config = dioxus::desktop::Config::new(); #[cfg(feature = "wdio")] { config = wdio_dioxus_bridge::install(config); } dioxus::LaunchBuilder::desktop().with_cfg(config).launch(App); } ``` Build with `cargo build --features wdio` for test builds, and `cargo build` for production. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### "bridge not available" or execute always returns undefined[​](#bridge-not-available-or-execute-always-returns-undefined "Direct link to \"bridge not available\" or execute always returns undefined") The bridge is not wired in. Check: 1. `wdio-dioxus-bridge = "1"` is in `[dependencies]` (not only `[dev-dependencies]`). 2. `wdio_dioxus_bridge::install(config)` is called inside `#[cfg(debug_assertions)]`. 3. You are building with `cargo build` (debug mode), not `cargo build --release`. 4. The `'dioxus:options'.application` path points to the debug binary. ### Compilation errors from `wdio-dioxus-bridge`[​](#compilation-errors-from-wdio-dioxus-bridge "Direct link to compilation-errors-from-wdio-dioxus-bridge") 1. Update your Rust toolchain: `rustup update` 2. Clear Cargo cache: `cargo clean && cargo build` 3. Check that `dioxus` version is `0.6+` ## See Also[​](#see-also "Direct link to See Also") * [Quick Start](/docs/desktop-testing/dioxus/quick-start.md) for minimal test setup * [API Reference](/docs/desktop-testing/dioxus/api.md) for available functions * [Usage Examples](/docs/desktop-testing/dioxus/usage-examples.md) for testing patterns * [Configuration](/docs/desktop-testing/dioxus/configuration.md) for service options * [wdio-dioxus-bridge README](https://github.com/webdriverio/desktop-mobile/blob/34f791f7984e1a32e816251f318ee64e48c23cf6/packages/dioxus-bridge/README.md) for bridge crate details --- Source: https://webdriver.io/docs/desktop-testing/dioxus/platform-support.md # Platform Support Complete guide to platform-specific requirements, limitations, and driver setup for Dioxus testing. ## Platform Support Overview[​](#platform-support-overview "Direct link to Platform Support Overview") | Platform | Supported | Driver Providers | Notes | | ----------- | --------- | -------------------------- | --------------------------------------------------------------------------------- | | **Windows** | ✅ Yes | `'embedded'`, `'external'` | `'embedded'` recommended; `'external'` requires wdio-dioxus-driver + msedgedriver | | **Linux** | ✅ Yes | `'embedded'` only | `'external'` blocked in v1 — upstream Dioxus PR pending | | **macOS** | ✅ Yes | `'embedded'` only | `'external'` not supported | ## Driver Providers[​](#driver-providers "Direct link to Driver Providers") ### `'embedded'`[​](#embedded "Direct link to embedded") * Type `Recommended Everywhere` The embedded WebDriver provider uses `wdio-dioxus-embedded-driver` wired into the app via `wdio_dioxus_bridge::install(config)`. No external driver process is needed. **Works on:** Windows, Linux, macOS **Requirements:** * `wdio-dioxus-bridge = "1"` in `Cargo.toml` * `wdio_dioxus_bridge::install(config)` in `main.rs` inside `#[cfg(debug_assertions)]` * Debug build of the app (`cargo build`) **Configuration:** ``` services: [['@wdio/dioxus-service', { driverProvider: 'embedded', // Default, recommended }]] ``` ### `'external'`[​](#external "Direct link to external") * Type `Windows Only in v1` The external provider uses `wdio-dioxus-driver` (a fork of `tauri-driver`) + `msedgedriver.exe`. **Works on:** Windows only in v1 **Not supported on:** Linux (blocked — see below), macOS (never supported) **Requirements:** * `wdio-dioxus-driver` installed via `cargo install wdio-dioxus-driver` * `msedgedriver.exe` (auto-managed by the service with `autoDownloadEdgeDriver: true`) **Configuration:** ``` services: [['@wdio/dioxus-service', { driverProvider: 'external', autoInstallDioxusDriver: true, autoDownloadEdgeDriver: true, }]] ``` ## Windows[​](#windows "Direct link to Windows") ### `'embedded'` Provider (Recommended)[​](#embedded-provider-recommended "Direct link to embedded-provider-recommended") No external driver needed. Ensure the bridge is in your app and use a debug build. ``` services: [['@wdio/dioxus-service', { driverProvider: 'embedded', appBinaryPath: './target/debug/my_app.exe', }]] ``` ### `'external'` Provider[​](#external-provider "Direct link to external-provider") Uses `wdio-dioxus-driver` → `msedgedriver.exe` → Dioxus app via WebView2 automation. **Setup:** 1. Build a debug binary: `cargo build` 2. Configure the service: ``` services: [['@wdio/dioxus-service', { driverProvider: 'external', autoInstallDioxusDriver: true, autoDownloadEdgeDriver: true, appBinaryPath: './target/debug/my_app.exe', }]] ``` The service auto-manages `msedgedriver.exe` to match the WebView2 version in your binary. See [Edge WebDriver (Windows)](/docs/desktop-testing/dioxus/edge-webdriver-windows.md) for detailed setup. ### Windows-Specific Features[​](#windows-specific-features "Direct link to Windows-Specific Features") * ✅ Full Dioxus invoke API via `browser.dioxus.execute()` * ✅ Command mocking * ✅ Log capture (frontend and backend) * ✅ Screenshot capture * ✅ Multiremote testing ### Windows Requirements[​](#windows-requirements "Direct link to Windows Requirements") * **Visual C++ Build Tools** or Visual Studio * **Rust toolchain** * **Node.js 18+** * For `'external'` provider: wdio-dioxus-driver + msedgedriver (auto-managed) ## Linux[​](#linux "Direct link to Linux") ### `'embedded'` Provider Only[​](#embedded-provider-only "Direct link to embedded-provider-only") `'external'` is blocked in v1 due to a missing upstream Dioxus API — the automation toggle that wdio-dioxus-driver needs to pass to Wry has not yet landed in the Dioxus/Wry codebase. This is tracked and will be enabled in v1.1 once the upstream PR merges. Attempting to set `driverProvider: 'external'` on Linux throws a `SevereServiceError` at startup with an explanatory message. **Configuration:** ``` services: [['@wdio/dioxus-service', { driverProvider: 'embedded', // The only supported option on Linux appBinaryPath: './target/debug/my_app', }]] ``` ### Linux Build Requirements[​](#linux-build-requirements "Direct link to Linux Build Requirements") Install WebKitGTK libraries (required to build Dioxus desktop apps): ``` # Debian/Ubuntu sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev # Fedora sudo dnf install -y webkit2gtk4.1-devel gtk3-devel # Arch Linux sudo pacman -S webkit2gtk-4.1 gtk3 ``` ### Headless Testing on Linux[​](#headless-testing-on-linux "Direct link to Headless Testing on Linux") To run tests without a display (CI/CD environments): ``` # With Xvfb sudo apt-get install -y xvfb xvfb-run -a npx wdio run wdio.conf.ts ``` ### Linux-Specific Features[​](#linux-specific-features "Direct link to Linux-Specific Features") * ✅ Full Dioxus invoke API * ✅ Command mocking * ✅ Log capture * ✅ Screenshot capture * ✅ Headless testing with Xvfb * ✅ Multiremote testing * ❌ `'external'` provider (v1 — v1.1 target) ### Linux Distribution Support[​](#linux-distribution-support "Direct link to Linux Distribution Support") | Distribution | Status | | ---------------------- | --------------------------------------- | | Debian / Ubuntu 22.04+ | ✅ Supported | | Fedora 40+ | ✅ Supported | | Arch Linux | ✅ Supported | | Alpine Linux | ❌ Not supported (musl incompatibility) | ## macOS[​](#macos "Direct link to macOS") ### `'embedded'` Provider Only[​](#embedded-provider-only-1 "Direct link to embedded-provider-only-1") `'external'` is not supported on macOS and never will be — it inherits the same WKWebView limitation as the upstream `tauri-driver` fork it is based on. **Configuration:** ``` services: [['@wdio/dioxus-service', { driverProvider: 'embedded', // Default, and the only option on macOS appBinaryPath: './target/debug/my_app', }]] ``` ### macOS-Specific Features[​](#macos-specific-features "Direct link to macOS-Specific Features") * ✅ Full Dioxus invoke API * ✅ Command mocking * ✅ Log capture * ✅ Screenshot capture * ✅ Multiremote testing * ❌ `'external'` provider (not supported, no timeline) ## Cross-Platform Tips[​](#cross-platform-tips "Direct link to Cross-Platform Tips") ### Recommended CI Matrix[​](#recommended-ci-matrix "Direct link to Recommended CI Matrix") ``` # .github/workflows/e2e.yml jobs: e2e: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable - name: Install Linux dependencies if: runner.os == 'Linux' run: sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev xvfb - uses: actions/setup-node@v4 with: node-version: '20' - run: npm install - run: cargo build - name: Run E2E (Linux, headless) if: runner.os == 'Linux' run: xvfb-run -a npm run test:e2e - name: Run E2E (Windows / macOS) if: runner.os != 'Linux' run: npm run test:e2e ``` ### Platform-Conditional Tests[​](#platform-conditional-tests "Direct link to Platform-Conditional Tests") ``` describe('Platform-specific features', () => { it('should handle Windows path format', function() { if (process.platform !== 'win32') { this.skip(); } // Windows-specific test }); it('should handle Linux file permissions', function() { if (process.platform !== 'linux') { this.skip(); } // Linux-specific test }); }); ``` ## Summary[​](#summary "Direct link to Summary") | Provider | Windows | Linux | macOS | | ------------ | ------- | --------- | ---------- | | `'embedded'` | ✅ | ✅ | ✅ | | `'external'` | ✅ | ❌ (v1.1) | ❌ (never) | Use `'embedded'` everywhere for the simplest, most consistent setup. ## See Also[​](#see-also "Direct link to See Also") * [Quick Start](/docs/desktop-testing/dioxus/quick-start.md) for setup instructions * [Edge WebDriver (Windows)](/docs/desktop-testing/dioxus/edge-webdriver-windows.md) for Windows `'external'` details * [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/dioxus/usage-examples.md # Usage Examples Practical examples for testing Dioxus applications with WebdriverIO. ## Basic Usage[​](#basic-usage "Direct link to Basic Usage") ### Element Interactions[​](#element-interactions "Direct link to Element Interactions") Standard WebDriver element interactions work with Dioxus apps: ``` describe('Dioxus App Interactions', () => { it('should interact with form elements', async () => { const input = await browser.$('input[name="username"]'); await input.setValue('test_user'); const button = await browser.$('button[type="submit"]'); await button.click(); const result = await browser.$('.result'); await result.waitForDisplayed(); const text = await result.getText(); expect(text).toBe('Success!'); }); it('should handle multiple elements', async () => { const buttons = await browser.$$('button'); expect(buttons).toHaveLength(5); for (const button of buttons) { const text = await button.getText(); console.log('Button text:', text); } }); }); ``` ## Execute API[​](#execute-api "Direct link to Execute API") ### Execute JavaScript in App Context[​](#execute-javascript-in-app-context "Direct link to Execute JavaScript in App Context") Use `browser.dioxus.execute()` to run JavaScript with access to Dioxus IPC: ``` describe('Dioxus API Access', () => { it('should access Dioxus invoke API', async () => { const result = await browser.dioxus.execute(({ invoke }) => { return invoke('get_config'); }); expect(result).toBeDefined(); }); it('should use async operations', async () => { const data = await browser.dioxus.execute(async ({ invoke }) => { const user = await invoke('get_user'); const permissions = await invoke('get_user_permissions', { userId: (user as any).id }); return { user, permissions }; }); expect(data.user).toBeDefined(); expect(data.permissions).toBeInstanceOf(Array); }); it('should execute with parameters', async () => { const username = 'test_user'; const result = await browser.dioxus.execute( (dx, name) => ({ received: name }), username ); expect(result.received).toBe('test_user'); }); it('should handle errors', async () => { try { await browser.dioxus.execute(() => { throw new Error('Test error'); }); } catch (error) { expect(error.message).toContain('Test error'); } }); }); ``` ## Mocking Dioxus Commands[​](#mocking-dioxus-commands "Direct link to Mocking Dioxus Commands") ### Mock Backend Commands[​](#mock-backend-commands "Direct link to Mock Backend Commands") ``` describe('Command Mocking', () => { it('should mock a simple command', async () => { const mock = await browser.dioxus.mock('get_app_version'); await mock.mockReturnValue('1.2.3'); const version = await browser.dioxus.execute(({ invoke }) => { return invoke('get_app_version'); }); expect(version).toBe('1.2.3'); }); it('should mock command with arguments', async () => { const mock = await browser.dioxus.mock('get_user'); await mock.mockReturnValue({ id: 1, name: 'John Doe' }); const user = await browser.dioxus.execute(({ invoke }) => { return invoke('get_user', { userId: 123 }); }); expect(user).toEqual({ id: 1, name: 'John Doe' }); }); it('should track mock calls', async () => { const mock = await browser.dioxus.mock('save_data'); await mock.mockReturnValue({ success: true }); await browser.dioxus.execute(async ({ invoke }) => { await invoke('save_data', { data: 'test1' }); await invoke('save_data', { data: 'test2' }); }); await mock.update(); expect(mock.mock.calls.length).toBeGreaterThanOrEqual(2); }); it('should handle errors in mocks', async () => { const mock = await browser.dioxus.mock('risky_operation'); await mock.mockRejectedValue(new Error('Operation failed')); try { await browser.dioxus.execute(({ invoke }) => { return invoke('risky_operation'); }); } catch (error) { expect(error.message).toBe('Operation failed'); } }); it('should restore mocks after test', async () => { const mock = await browser.dioxus.mock('get_data'); await mock.mockReturnValue({ mocked: true }); await mock.mockRestore(); // Now calls the real command const result = await browser.dioxus.execute(({ invoke }) => { return invoke('get_data'); }); expect(result).toBeDefined(); }); }); ``` ## Testing Custom Commands[​](#testing-custom-commands "Direct link to Testing Custom Commands") ``` describe('Custom Dioxus Commands', () => { it('should call custom command with simple return', async () => { const greeting = await browser.dioxus.execute(({ invoke }) => { return invoke('greet', { name: 'Dioxus' }); }); expect(greeting).toBe('Hello, Dioxus!'); }); it('should call command returning object', async () => { const config = await browser.dioxus.execute(({ invoke }) => { return invoke('get_config'); }); expect(config).toHaveProperty('version'); expect(config).toHaveProperty('isDev'); }); }); ``` ## Log Capture[​](#log-capture "Direct link to Log Capture") ``` describe('Log Capture', () => { it('should verify console logs', async () => { // Log capture enabled in wdio.conf.ts: // captureBackendLogs: true // captureFrontendLogs: true const logs = await browser.getLogs('browser'); await browser.$('button').click(); const newLogs = await browser.getLogs('browser'); const hasExpectedLog = newLogs.some(log => log.message.includes('Button clicked') ); expect(hasExpectedLog).toBe(true); }); }); ``` ## Multi-Window Testing[​](#multi-window-testing "Direct link to Multi-Window Testing") ``` describe('Multi-Window Testing', () => { it('should list available windows', async () => { const windows = await browser.dioxus.listWindows(); console.log('Available windows:', windows); expect(windows).toContain('main'); expect(windows).toContain('settings'); }); it('should switch between windows', async () => { const mainContent = await browser.dioxus.execute(() => { return document.querySelector('h1')?.textContent; }); expect(mainContent).toBe('Main Window'); await browser.dioxus.switchWindow('settings'); const settingsContent = await browser.dioxus.execute(() => { return document.querySelector('h1')?.textContent; }); expect(settingsContent).toBe('Settings'); await browser.dioxus.switchWindow('main'); }); it('should handle non-existent window gracefully', async () => { await expect(browser.dioxus.switchWindow('nonexistent')).rejects.toThrow( 'Window label "nonexistent" not found' ); }); }); ``` Configuration for a default window: ``` // wdio.conf.ts capabilities: [{ browserName: 'dioxus', 'wdio:dioxusServiceOptions': { windowLabel: 'settings', // Default to settings window }, }] ``` ## Deeplink Testing[​](#deeplink-testing "Direct link to Deeplink Testing") ``` describe('Deeplink Tests', () => { it('should handle custom protocol deeplinks', async () => { await browser.dioxus.triggerDeeplink('myapp://open?file=test.txt'); await browser.waitUntil(async () => { const openedFile = await browser.dioxus.execute(() => { return globalThis.lastOpenedFile; }); return openedFile === 'test.txt'; }, { timeout: 5000, timeoutMsg: 'App did not handle the deeplink', }); }); }); ``` ## Multiremote Testing[​](#multiremote-testing "Direct link to Multiremote Testing") ``` describe('Multiremote — Multiple App Instances', () => { it('should mock different commands per instance', async () => { const mock1 = await browser.app1.dioxus.mock('get_user'); await mock1.mockReturnValue({ id: 1, name: 'User1' }); const mock2 = await browser.app2.dioxus.mock('get_user'); await mock2.mockReturnValue({ id: 2, name: 'User2' }); const user1 = await browser.app1.dioxus.execute(({ invoke }) => { return invoke('get_user'); }); const user2 = await browser.app2.dioxus.execute(({ invoke }) => { return invoke('get_user'); }); expect(user1.id).toBe(1); expect(user2.id).toBe(2); }); }); ``` ## Standalone Session[​](#standalone-session "Direct link to Standalone Session") Use `startWdioSession` to manage a session outside of the WebdriverIO test runner: ``` import { startWdioSession } from '@wdio/dioxus-service'; const browser = await startWdioSession({ browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, 'wdio:dioxusServiceOptions': { driverProvider: 'embedded', }, }); const heading = await browser.$('h1'); console.log(await heading.getText()); await browser.deleteSession(); ``` ## Common Testing Patterns[​](#common-testing-patterns "Direct link to Common Testing Patterns") ### Wait for Async Operations[​](#wait-for-async-operations "Direct link to Wait for Async Operations") ``` it('should wait for async data load', async () => { const loadButton = await browser.$('button[data-testid="load"]'); await loadButton.click(); const spinner = await browser.$('.loading-spinner'); await spinner.waitForDisplayed({ reverse: true, timeout: 5000 }); const data = await browser.$('.data-content'); expect(await data.isDisplayed()).toBe(true); }); ``` ### Test Error Handling[​](#test-error-handling "Direct link to Test Error Handling") ``` it('should display error message on failure', async () => { const mock = await browser.dioxus.mock('fetch_data'); await mock.mockRejectedValue(new Error('Network error')); const button = await browser.$('button[data-testid="fetch"]'); await button.click(); const error = await browser.$('.error-message'); await error.waitForDisplayed(); const text = await error.getText(); expect(text).toContain('Network error'); }); ``` ### Test State Persistence[​](#test-state-persistence "Direct link to Test State Persistence") ``` it('should persist state across reload', async () => { await browser.dioxus.execute(async ({ invoke }) => { await invoke('set_user_preference', { theme: 'dark' }); }); await browser.execute(() => window.location.reload()); const theme = await browser.dioxus.execute(({ invoke }) => { return invoke('get_user_preference', { key: 'theme' }); }); expect(theme).toBe('dark'); }); ``` ## See Also[​](#see-also "Direct link to See Also") * [API Reference](/docs/desktop-testing/dioxus/api.md) for complete API documentation * [Configuration](/docs/desktop-testing/dioxus/configuration.md) for testing setup options * [Log Forwarding](/docs/desktop-testing/dioxus/log-forwarding.md) for logging patterns * [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md) for bridge configuration * [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/dioxus/browser-mode.md # Browser Mode Browser mode lets you test your Dioxus frontend UI in plain Chrome against a running dev server — no Dioxus binary, no driver. The Dioxus invoke API is intercepted at the JavaScript boundary in the renderer, so you can mock individual commands and assert on call arguments just like in native mode. ## Overview[​](#overview "Direct link to Overview") ### What Is It?[​](#what-is-it "Direct link to What Is It?") Browser mode is a **frontend-only test mode**. Your frontend code runs for real in Chrome; the Dioxus Rust backend is replaced by mocks you define per command. Same WDIO API, same frontend code path — the only thing that changes is what's on the other end of `invoke(...)`. In normal (`native`) mode the service launches your compiled Dioxus app, drives it via the configured driver provider, and communicates with the backend through the bridge. Browser mode replaces all of that with a standard Chrome session: it sets `browserName` to `'chrome'`, navigates to your dev server URL, and injects a lightweight script that patches the invoke API so your Dioxus commands can be intercepted in tests. ### Why Use It?[​](#why-use-it "Direct link to Why Use It?") * **No build step needed** — point the service at a dev server and start testing immediately. * **Fast feedback** — no Dioxus startup, no Rust compilation, no driver negotiation. * **Standard browser devtools** — Chrome DevTools and HMR work as normal during development. ### When to Use It[​](#when-to-use-it "Direct link to When to Use It") Browser mode is the right choice when your tests are renderer-focused: asserting UI state, verifying that components call the correct Dioxus commands with the right arguments, or checking that the renderer handles mock responses correctly. It is **not** suitable when your tests need to: * Call `browser.dioxus.execute()` to run code with access to the bridge * Test window management with `browser.dioxus.switchWindow()` or `browser.dioxus.listWindows()` * Use `browser.dioxus.triggerDeeplink()` * Assert on real command round-trips to a running Rust backend For those scenarios use native mode (the default). ## Setup[​](#setup "Direct link to Setup") ### 1. Start Your Dev Server[​](#1-start-your-dev-server "Direct link to 1. Start Your Dev Server") Browser mode requires a running dev server that serves your frontend code. Or let the service **start and stop it for you** with the optional `devServer` option (see [Auto-managing the dev server](#auto-managing-the-dev-server) below) — then you don't need to start it yourself. ### 2. Configure the Service[​](#2-configure-the-service "Direct link to 2. Configure the Service") Set `mode: 'browser'` and provide `devServerUrl` in your WDIO configuration. No `appBinaryPath`, `dioxus:options`, or driver config is needed. *`wdio.conf.ts`* ``` export const config = { services: ['@wdio/dioxus-service'], capabilities: [ { browserName: 'dioxus', 'wdio:dioxusServiceOptions': { mode: 'browser', devServerUrl: 'http://localhost:8080', }, }, ], }; ``` You can also set `mode` and `devServerUrl` at the global service level: ``` export const config = { services: [ [ '@wdio/dioxus-service', { mode: 'browser', devServerUrl: 'http://localhost:8080', }, ], ], capabilities: [ { browserName: 'dioxus' }, ], }; ``` Capability-level options take precedence over service-level ones. All capabilities in a session must use the same mode; mixing `'native'` and `'browser'` across capabilities throws a `SevereServiceError` at startup. ## Auto-managing the dev server[​](#auto-managing-the-dev-server "Direct link to Auto-managing the dev server") By default you start the dev server yourself. The optional `devServer` service option makes the service **spawn it in `onPrepare`, wait until `devServerUrl` is reachable, and tear it down on completion** (and on a startup failure). It takes three forms: ``` // 1. A shell command (the common case) devServer: 'pnpm dev' // 2. An object — command plus cwd/env/timeout, and reuse control devServer: { command: 'pnpm dev', cwd: './app', env: { NODE_ENV: 'test' }, timeoutMs: 60_000, // readiness budget (default 60s, 120s in CI) reuseExistingServer: true, // default: reuse a running server locally, always spawn in CI } // 3. A function — start it programmatically and return how to close it. // No subprocess/quoting/child-kill involved; the returned `url` supplies/overrides devServerUrl. devServer: async () => { const server = await createServer(); await server.listen(); return { url: server.resolvedUrls.local[0], close: () => server.close() }; } ``` Notes: * `devServer` is a **service-level** option (one dev server per run) and only applies in browser mode. * With `reuseExistingServer` (default off in CI, on locally), if `devServerUrl` is already reachable the spawn is skipped — handy when you already have `pnpm dev` running during local iteration. * The command form spawns in a shell and tears down the whole process tree (so `pnpm dev → vite → esbuild` grandchildren don't orphan); the function form avoids subprocesses entirely. * The same option is available on the Tauri, Electron, and Electrobun services. ## IPC Mocking[​](#ipc-mocking "Direct link to IPC Mocking") ### How It Works[​](#how-it-works "Direct link to How It Works") When the session starts, the service injects a script into the page that: 1. Creates `window.__wdio_mocks__` — a registry of per-command mock functions. 2. Patches the Dioxus invoke API to look up `window.__wdio_mocks__[command]` and call it; throws if the command has no registered mock. The injection script runs again after every `browser.url()` navigation because a page load wipes `window` state. ### Mocking a Command[​](#mocking-a-command "Direct link to Mocking a Command") ``` const mockReadFile = await browser.dioxus.mock('read_file'); await mockReadFile.mockResolvedValue('mocked file content'); ``` ### Asserting on Calls[​](#asserting-on-calls "Direct link to Asserting on Calls") After triggering the relevant UI action, call `update()` to sync call data from the browser-side spy to the outer mock object, then assert: ``` await $('button#load-file').click(); await mockReadFile.update(); expect(mockReadFile).toHaveBeenCalledTimes(1); expect(mockReadFile.mock.calls[0]).toEqual([{ path: '/some/file' }]); ``` Element commands (`click`, `doubleClick`, `setValue`, `clearValue`) trigger `update()` automatically on all active mocks. ### Setting Implementations[​](#setting-implementations "Direct link to Setting Implementations") ``` // Return a fixed value await mockReadFile.mockReturnValue('file content'); // Resolve a promise (for async commands) await mockReadFile.mockResolvedValue('file content'); // Use a function for dynamic responses await mockReadFile.mockImplementation((args) => { return `content of ${args.path}`; }); // Respond differently on first call, then fall back await mockReadFile.mockResolvedValueOnce('first call content'); await mockReadFile.mockResolvedValue('default content'); ``` ### Restoring a Mock[​](#restoring-a-mock "Direct link to Restoring a Mock") ``` await mockReadFile.mockRestore(); ``` ## Events[​](#events "Direct link to Events") Events are not supported in either mode — Dioxus has no native event bus, so there is no `browser.dioxus.emitEvent()` (see [`@wdio/native-types`](https://github.com/webdriverio/desktop-mobile/blob/34f791f7984e1a32e816251f318ee64e48c23cf6/packages/native-types/src/dioxus.ts)). This is a service-wide limitation, not specific to browser mode. ## Mock Lifecycle Across Tests[​](#mock-lifecycle-across-tests "Direct link to Mock Lifecycle Across Tests") ### `mock(command)` Is Idempotent[​](#mockcommand-is-idempotent "Direct link to mockcommand-is-idempotent") Calling `browser.dioxus.mock(command)` multiple times for the same command is safe, but the service always fully resets the existing mock (via `mockReset()`) before returning it — both call history and any previously-set implementation are cleared on every call. Set the implementation in `beforeEach` rather than relying on `beforeAll` setup persisting. ``` describe('File panel', () => { let mockReadFile: DioxusMock; beforeEach(async () => { mockReadFile = await browser.dioxus.mock('read_file'); await mockReadFile.mockResolvedValue('default content'); }); it('displays file content', async () => { await $('button#load-file').click(); await mockReadFile.update(); expect(mockReadFile).toHaveBeenCalledTimes(1); }); }); ``` ## Navigation[​](#navigation "Direct link to Navigation") `browser.url()` is patched by the service to re-run the IPC injection script after every navigation. This re-creates `window.__wdio_mocks__` (as an empty object). Existing mock handles remain valid as JS objects, but their browser-side entries are gone. To recover, call `mockRestore()` first and then `mock(command)` to re-create the browser-side entry. ## Limitations[​](#limitations "Direct link to Limitations") | Feature | Browser Mode | | -------------------------------------------- | ---------------------------------------------------- | | `browser.dioxus.execute()` | Throws — no Dioxus backend or bridge | | `browser.dioxus.triggerDeeplink()` | Throws — no Dioxus process | | `browser.dioxus.switchWindow()` | Throws — multi-window requires a native Dioxus app | | `browser.dioxus.listWindows()` | Throws — same reason as `switchWindow()` | | Backend log capture (`captureBackendLogs`) | Not available — no Rust process | | Frontend log capture (`captureFrontendLogs`) | Available — Chrome session, standard console capture | ## Multiremote[​](#multiremote "Direct link to Multiremote") Each named multiremote instance gets its own isolated mock registry. ``` export const config = { services: [['@wdio/dioxus-service', { mode: 'browser' }]], capabilities: { app1: { capabilities: { browserName: 'dioxus', 'wdio:dioxusServiceOptions': { devServerUrl: 'http://localhost:8080' }, }, }, app2: { capabilities: { browserName: 'dioxus', 'wdio:dioxusServiceOptions': { devServerUrl: 'http://localhost:8080' }, }, }, }, }; ``` ``` const mock1 = await browser.getInstance('app1').dioxus.mock('read_file'); const mock2 = await browser.getInstance('app2').dioxus.mock('read_file'); await mock1.mockResolvedValue('content from app1'); await mock2.mockResolvedValue('content from app2'); ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### `"unmocked Dioxus command in browser mode: "`[​](#unmocked-dioxus-command-in-browser-mode-command "Direct link to unmocked-dioxus-command-in-browser-mode-command") Your renderer called `invoke(command)` before a mock was registered. Call `browser.dioxus.mock(command)` before the code path that triggers the command. ### `"unmocked Dioxus command in browser mode"` error after navigation[​](#unmocked-dioxus-command-in-browser-mode-error-after-navigation "Direct link to unmocked-dioxus-command-in-browser-mode-error-after-navigation") The browser-side entry was wiped by navigation. Call `mock.mockRestore()` first to delete the worker-side entry, then `browser.dioxus.mock(command)` to re-create both sides. ### Dev server not running[​](#dev-server-not-running "Direct link to Dev server not running") The service throws a `SevereServiceError` if `devServerUrl` is missing or not a valid URL. A connection-refused error from Chrome means the dev server is not running — start it before launching the test suite. --- Source: https://webdriver.io/docs/desktop-testing/dioxus/log-forwarding.md # Log Forwarding Capture and forward logs from your Dioxus application to WebdriverIO's logger system. ## Overview[​](#overview "Direct link to Overview") The Dioxus service can capture and forward logs from both the Rust backend and the frontend webview console to WebdriverIO's logger system. This allows you to see Dioxus application logs seamlessly integrated with your test output. ## Enabling Log Forwarding[​](#enabling-log-forwarding "Direct link to Enabling Log Forwarding") Log forwarding is disabled by default. Enable it via service options: ``` // wdio.conf.ts export const config = { services: [ ['@wdio/dioxus-service', { captureBackendLogs: true, // Capture Rust logs from the app process captureFrontendLogs: true, // Capture console logs from the webview backendLogLevel: 'info', // Minimum backend log level (default: 'info') frontendLogLevel: 'info', // Minimum frontend log level (default: 'info') }], ], capabilities: [ { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, }, ], }; ``` ## Log Levels[​](#log-levels "Direct link to Log Levels") Both backend and frontend log capture support the following log levels (in order of priority): * `trace` - Most verbose * `debug` - Debug information * `info` - Informational messages (default) * `warn` - Warning messages * `error` - Error messages Only logs at the configured level and above will be captured. For example, with `backendLogLevel: 'info'`, only `info`, `warn`, and `error` logs are captured. ## Log Format[​](#log-format "Direct link to Log Format") Captured logs are formatted with context tags: * Backend logs: `[Dioxus:Backend] message` * Frontend logs: `[Dioxus:Frontend] message` * Multiremote logs: `[Dioxus:Backend:instanceId] message` / `[Dioxus:Frontend:instanceId] message` ## Backend Log Capture[​](#backend-log-capture "Direct link to Backend Log Capture") Backend log capture reads Rust logs from the Dioxus application process. These logs are generated using the Rust `log` crate: ``` // In your Dioxus app (add log crate to Cargo.toml) log::info!("This is an info log"); log::warn!("This is a warning"); log::error!("This is an error"); ``` Enable the `log` crate in your `Cargo.toml`: ``` [dependencies] dioxus = { version = "0.6", features = ["desktop"] } log = "0.4" ``` > **Note:** The `log` crate is a no-op façade until a concrete backend registers itself as the global logger. During WDIO test runs, `wdio-dioxus-bridge` installs its own subscriber automatically. For non-WDIO runs (development, production), add a backend such as `tracing-subscriber` or `env_logger` so your `log::*!()` calls produce output. The service automatically filters driver-level logs and only captures logs from your Dioxus application. ## Frontend Log Capture[​](#frontend-log-capture "Direct link to Frontend Log Capture") Frontend log capture uses the WebDriver `getLogs` API to retrieve console logs from the webview: ``` // In your Dioxus frontend (JavaScript/TypeScript) console.info('This is an info log'); console.warn('This is a warning'); console.error('This is an error'); ``` Frontend logs are captured periodically and before each WebDriver command. ## Independent Configuration[​](#independent-configuration "Direct link to Independent Configuration") Backend and frontend log capture can be configured independently: ``` services: [ ['@wdio/dioxus-service', { captureBackendLogs: true, captureFrontendLogs: false, backendLogLevel: 'debug', }], ], ``` ## Multiremote Support[​](#multiremote-support "Direct link to Multiremote Support") In multiremote scenarios, logs are captured per instance with instance IDs in the log context: ``` capabilities: { browserA: { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, }, browserB: { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_app', }, }, }, services: [ ['@wdio/dioxus-service', { captureBackendLogs: true, captureFrontendLogs: true, }], ], ``` Logs will appear as: * `[Dioxus:Backend:browserA] message` * `[Dioxus:Frontend:browserB] message` ## Performance Considerations[​](#performance-considerations "Direct link to Performance Considerations") * Log capture is optional and disabled by default to avoid overhead. * Frontend log capture uses periodic polling (every 1 second) which has minimal performance impact. * Backend log parsing is efficient and non-blocking. * Log level filtering reduces the number of logs processed. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### Logs not appearing[​](#logs-not-appearing "Direct link to Logs not appearing") * Ensure `captureBackendLogs` or `captureFrontendLogs` is set to `true`. * Check that your log level is appropriate (logs below the configured level won't appear). * Verify logs are being written to stdout (backend) or console (frontend). * For backend logs: ensure the `log` crate is properly initialized in your Rust app. ### Too many logs[​](#too-many-logs "Direct link to Too many logs") * Increase the log level (e.g., from `debug` to `info`) to filter out verbose logs. * Disable log capture for one source if you only need backend or frontend logs. ### Frontend logs not captured[​](#frontend-logs-not-captured "Direct link to Frontend logs not captured") * Some WebDriver implementations may not support the `getLogs` API. * The service will silently fail if `getLogs` is not supported. * Backend logs will still work in this case. ## See Also[​](#see-also "Direct link to See Also") * [Configuration](/docs/desktop-testing/dioxus/configuration.md) for all service options * [Usage Examples](/docs/desktop-testing/dioxus/usage-examples.md) for logging patterns * [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/dioxus/edge-webdriver-windows.md # Edge WebDriver on Windows ## Overview[​](#overview "Direct link to Overview") On Windows, Dioxus applications use Microsoft Edge WebView2, which requires `msedgedriver.exe` for WebDriver automation when using the `'external'` driver provider. The dioxus-service automatically handles Edge WebDriver version matching to prevent version mismatch errors. This document only applies to the `'external'` driver provider on Windows. The `'embedded'` provider (recommended) has no Edge WebDriver dependency. ## The Problem[​](#the-problem "Direct link to The Problem") Tests using `driverProvider: 'external'` fail on Windows when the Edge browser version doesn't match the installed msedgedriver version: ``` Error: This version of Microsoft Edge WebDriver only supports Microsoft Edge version 144. Current browser version is 143.0.3650.139 ``` ## The Solution[​](#the-solution "Direct link to The Solution") When `driverProvider: 'external'` and `autoDownloadEdgeDriver: true`, the dioxus-service automatically: 1. **Detects** your Edge browser (WebView2) version 2. **Checks** if a matching msedgedriver.exe exists 3. **Downloads** the correct version if needed 4. **Configures** PATH to use the downloaded driver ## Configuration[​](#configuration "Direct link to Configuration") ### Auto-Download (Recommended)[​](#auto-download-recommended "Direct link to Auto-Download (Recommended)") By default, auto-download is **enabled** for the `'external'` provider: ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'external', appBinaryPath: './target/debug/my_app.exe', // autoDownloadEdgeDriver: true (default) }] ] ``` ### Manual Management[​](#manual-management "Direct link to Manual Management") Disable auto-download if you prefer to manage drivers yourself: ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'external', appBinaryPath: './target/debug/my_app.exe', autoDownloadEdgeDriver: false, }] ] ``` With auto-download disabled, you must ensure msedgedriver matches your Edge version manually. ## How It Works[​](#how-it-works "Direct link to How It Works") ### 1. Version Detection[​](#1-version-detection "Direct link to 1. Version Detection") The service detects the WebView2/Edge version from: * Windows Registry: `HKLM\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{56EB18F8-B008-4CBD-B6D2-8C97FE7E9062}` ### 2. Driver Check[​](#2-driver-check "Direct link to 2. Driver Check") Checks if msedgedriver.exe in PATH matches the detected Edge version (major version comparison). ### 3. Download & Install[​](#3-download--install "Direct link to 3. Download & Install") If a mismatch is detected: * Downloads msedgedriver from `https://msedgedriver.azureedge.net/{version}/` * Caches in temp directory: `%TEMP%\msedgedriver\{majorVersion}\` * Adds to process PATH for test execution ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### "Could not detect Edge version"[​](#could-not-detect-edge-version "Direct link to \"Could not detect Edge version\"") **Cause:** Edge not installed or registry keys missing. **Solution:** Install Microsoft Edge from ### "Failed to download msedgedriver"[​](#failed-to-download-msedgedriver "Direct link to \"Failed to download msedgedriver\"") **Causes:** * Network/proxy issues * Microsoft's CDN temporarily unavailable **Solutions:** 1. Check internet connection and proxy settings 2. Retry — CDN may be temporarily down 3. Download manually from 4. Place `msedgedriver.exe` in PATH ### "Version mismatch" even after download[​](#version-mismatch-even-after-download "Direct link to \"Version mismatch\" even after download") **Cause:** Another msedgedriver.exe earlier in PATH is being used. **Solution:** Check PATH order: ``` where msedgedriver.exe ``` Ensure the correct version appears first. ### CI/GitHub Actions Issues[​](#cigithub-actions-issues "Direct link to CI/GitHub Actions Issues") GitHub Actions runners may have outdated Edge. Update if needed: ``` - name: Update Edge (if needed) if: runner.os == 'Windows' run: choco upgrade microsoft-edge -y - name: Run tests run: npm run test:e2e ``` ## Manual Driver Management[​](#manual-driver-management "Direct link to Manual Driver Management") If you disable auto-download: ### Check Edge Version[​](#check-edge-version "Direct link to Check Edge Version") ``` reg query "HKLM\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{56EB18F8-B008-4CBD-B6D2-8C97FE7E9062}" /v pv ``` ### Download Matching Driver[​](#download-matching-driver "Direct link to Download Matching Driver") 1. Visit 2. Download the version matching your Edge major version 3. Extract `msedgedriver.exe` 4. Add to PATH or place in project directory ### Verify Installation[​](#verify-installation "Direct link to Verify Installation") ``` msedgedriver.exe --version ``` ## Cache Location[​](#cache-location "Direct link to Cache Location") Downloaded drivers are cached at: ``` %TEMP%\msedgedriver\{majorVersion}\msedgedriver.exe ``` Example: `C:\Users\YourName\AppData\Local\Temp\msedgedriver\143\msedgedriver.exe` ## Platform Notes[​](#platform-notes "Direct link to Platform Notes") * **Windows**: Edge driver management runs when `driverProvider: 'external'` * **Linux**: `'external'` provider is blocked in v1 — use `'embedded'` * **macOS**: `'external'` provider is not supported — use `'embedded'` ## Recommendation[​](#recommendation "Direct link to Recommendation") Use `driverProvider: 'embedded'` for the simplest Windows setup — it works on all platforms without any external driver or Edge WebDriver management. ## See Also[​](#see-also "Direct link to See Also") * [Platform Support](/docs/desktop-testing/dioxus/platform-support.md) for the full provider matrix * [Configuration](/docs/desktop-testing/dioxus/configuration.md) for `autoDownloadEdgeDriver` and related options * [Troubleshooting](/docs/desktop-testing/dioxus/troubleshooting.md) for common issues --- Source: https://webdriver.io/docs/desktop-testing/dioxus/deeplink-testing.md # Deeplink Testing The service provides the ability to test custom protocol handlers and deeplinks in your Dioxus application using the `browser.dioxus.triggerDeeplink()` method. ## Overview[​](#overview "Direct link to Overview") ### What Is Deeplink Testing?[​](#what-is-deeplink-testing "Direct link to What Is Deeplink Testing?") Deeplink testing allows you to verify that your Dioxus application correctly handles custom protocol URLs (e.g., `myapp://action?param=value`). This is essential when your app registers as a protocol handler and needs to respond to URLs opened from external sources. ### When Should You Use It?[​](#when-should-you-use-it "Direct link to When Should You Use It?") Use `browser.dioxus.triggerDeeplink()` when you need to: * Test that your app correctly handles custom protocol URLs * Verify deeplink parameter parsing and routing logic * Test protocol handler registration and activation * Validate deeplink-driven workflows in your application ## Prerequisites[​](#prerequisites "Direct link to Prerequisites") ### Protocol Registration[​](#protocol-registration "Direct link to Protocol Registration") Your Dioxus app must register its custom protocol scheme with the operating system. The mechanism depends on your app's packaging setup — consult your OS or Dioxus desktop documentation for registering a URL scheme handler. ## Basic Usage[​](#basic-usage "Direct link to Basic Usage") ### Simple Example[​](#simple-example "Direct link to Simple Example") ``` describe('Protocol Handler Tests', () => { it('should handle custom protocol deeplinks', async () => { await browser.dioxus.triggerDeeplink('myapp://open?file=test.txt'); await browser.waitUntil(async () => { const openedFile = await browser.dioxus.execute(() => { return globalThis.lastOpenedFile; }); return openedFile === 'test.txt'; }, { timeout: 5000, timeoutMsg: 'App did not handle the deeplink', }); }); }); ``` ### Complex URL Parameters[​](#complex-url-parameters "Direct link to Complex URL Parameters") ``` it('should preserve query parameters', async () => { await browser.dioxus.triggerDeeplink( 'myapp://action?param1=value1¶m2=value2' ); const receivedParams = await browser.dioxus.execute(() => { return globalThis.lastDeeplinkParams; }); expect(receivedParams.param1).toBe('value1'); expect(receivedParams.param2).toBe('value2'); }); ``` ### Error Handling[​](#error-handling "Direct link to Error Handling") ``` it('should reject invalid protocols', async () => { await expect( browser.dioxus.triggerDeeplink('https://example.com') ).rejects.toThrow('Invalid deeplink protocol'); }); ``` ## Platform Behavior[​](#platform-behavior "Direct link to Platform Behavior") The service handles platform-specific differences automatically: ### Windows[​](#windows "Direct link to Windows") * Uses `cmd /c start` to trigger the deeplink. ### macOS[​](#macos "Direct link to macOS") * Uses `open` to trigger the deeplink. ### Linux[​](#linux "Direct link to Linux") * Uses `xdg-open` to trigger the deeplink. ## App Implementation[​](#app-implementation "Direct link to App Implementation") Your Dioxus app needs to listen for deeplinks. The implementation depends on how you register the URL scheme. A typical pattern: ``` use dioxus::prelude::*; #[component] fn App() -> Element { let deeplink = use_signal(|| String::new()); // Listen for OS deeplink events via your URL scheme handler mechanism // and update the `deeplink` signal rsx! { div { p { "Last deeplink: {deeplink}" } } } } ``` Store deeplink data in a globally accessible location so tests can read it via `browser.dioxus.execute()`. ## Common Issues[​](#common-issues "Direct link to Common Issues") ### Deeplinks Not Received in App[​](#deeplinks-not-received-in-app "Direct link to Deeplinks Not Received in App") **Symptom:** The deeplink is triggered but your app doesn't receive it. **Possible Causes:** 1. **Protocol not registered** — verify your app is registered as the handler for the scheme. 2. **Listener not set up before trigger** — ensure your deeplink listener is active before calling `triggerDeeplink()`. 3. **Timing** — the OS may take a moment to route the deeplink to your running app. ### Timing Issues[​](#timing-issues "Direct link to Timing Issues") **Solution:** Use `waitUntil` to wait for the app to process the deeplink: ``` await browser.dioxus.triggerDeeplink('myapp://action'); await browser.waitUntil(async () => { const processed = await browser.dioxus.execute(() => { return globalThis.deeplinkProcessed; }); return processed === true; }, { timeout: 5000, timeoutMsg: 'App did not process the deeplink within 5 seconds', }); ``` ### Invalid Protocol Error[​](#invalid-protocol-error "Direct link to Invalid Protocol Error") Only use custom protocol schemes — not `https`, `http`, or `file`: ``` // Correct — custom protocol await browser.dioxus.triggerDeeplink('myapp://action'); // Incorrect — web protocol (throws) await browser.dioxus.triggerDeeplink('https://example.com'); ``` ## See Also[​](#see-also "Direct link to See Also") * [API Reference](/docs/desktop-testing/dioxus/api.md) for complete method documentation * [Usage Examples](/docs/desktop-testing/dioxus/usage-examples.md) for additional patterns --- Source: https://webdriver.io/docs/desktop-testing/dioxus/coexistence.md # Coexistence This guide explains how to run `@wdio/dioxus-service` alongside `@wdio/tauri-service` and `@wdio/electron-service` in the same monorepo. ## Overview[​](#overview "Direct link to Overview") Each service is designed to be independent. They share `@wdio/native-types` for TypeScript types and `@wdio/native-spy` for mock utilities, but they do not interfere with each other when configured correctly. ## Capability Disambiguation[​](#capability-disambiguation "Direct link to Capability Disambiguation") Each service identifies its target app via `browserName`: | Service | `browserName` | | ------------------------ | ------------- | | `@wdio/dioxus-service` | `'dioxus'` | | `@wdio/tauri-service` | `'tauri'` | | `@wdio/electron-service` | `'electron'` | When a WDIO runner starts, each service checks the `browserName` of each capability and only takes ownership of capabilities matching its framework. Unrecognized capabilities are passed through untouched. ## Separate Config Files Per Service[​](#separate-config-files-per-service "Direct link to Separate Config Files Per Service") The recommended approach is to maintain a separate `wdio.conf.ts` per framework: ``` your-monorepo/ ├── apps/ │ ├── dioxus-app/ # Dioxus app source │ ├── tauri-app/ # Tauri app source │ └── electron-app/ # Electron app source ├── e2e/ │ ├── test/ │ │ ├── dioxus/ # Dioxus E2E specs │ │ ├── tauri/ # Tauri E2E specs │ │ └── electron/ # Electron E2E specs │ ├── wdio.dioxus.conf.ts │ ├── wdio.tauri.conf.ts │ └── wdio.electron.conf.ts ``` ### `wdio.dioxus.conf.ts`[​](#wdiodioxusconfts "Direct link to wdiodioxusconfts") ``` export const config = { specs: ['./test/dioxus/**/*.spec.ts'], services: [['@wdio/dioxus-service', { driverProvider: 'embedded', }]], capabilities: [{ browserName: 'dioxus', 'dioxus:options': { application: '../apps/dioxus-app/target/debug/dioxus_app', }, }], }; ``` ### `wdio.tauri.conf.ts`[​](#wdiotauriconfts "Direct link to wdiotauriconfts") ``` export const config = { specs: ['./test/tauri/**/*.spec.ts'], services: [['@wdio/tauri-service', { driverProvider: 'embedded', }]], capabilities: [{ browserName: 'tauri', 'tauri:options': { application: '../apps/tauri-app/src-tauri/target/debug/tauri_app', }, }], }; ``` ### `wdio.electron.conf.ts`[​](#wdioelectronconfts "Direct link to wdioelectronconfts") ``` export const config = { specs: ['./test/electron/**/*.spec.ts'], services: [['@wdio/electron-service', { appBinaryPath: '../apps/electron-app/dist/my-app', }]], capabilities: [{ browserName: 'electron', }], }; ``` ## Running Specific Suites[​](#running-specific-suites "Direct link to Running Specific Suites") ``` # Dioxus tests only npx wdio run wdio.dioxus.conf.ts # Tauri tests only npx wdio run wdio.tauri.conf.ts # Electron tests only npx wdio run wdio.electron.conf.ts ``` Or with package scripts: ``` { "scripts": { "test:e2e:dioxus": "wdio run wdio.dioxus.conf.ts", "test:e2e:tauri": "wdio run wdio.tauri.conf.ts", "test:e2e:electron": "wdio run wdio.electron.conf.ts", "test:e2e": "run-p test:e2e:*" } } ``` ## Shared Types — No Conflicts[​](#shared-types--no-conflicts "Direct link to Shared Types — No Conflicts") All three services share `@wdio/native-types` for TypeScript type definitions. The types for each service are namespaced to avoid conflicts: | Type | Service | | ------------------------ | ------------------------ | | `DioxusServiceOptions` | `@wdio/dioxus-service` | | `TauriServiceOptions` | `@wdio/tauri-service` | | `ElectronServiceOptions` | `@wdio/electron-service` | The capability extensions are also namespaced: | Capability key | Service | | ------------------------------- | -------- | | `'dioxus:options'` | Dioxus | | `'wdio:dioxusServiceOptions'` | Dioxus | | `'tauri:options'` | Tauri | | `'wdio:tauriServiceOptions'` | Tauri | | `'wdio:electronServiceOptions'` | Electron | ## Mixed-Service Test Session (Advanced)[​](#mixed-service-test-session-advanced "Direct link to Mixed-Service Test Session (Advanced)") If you want to run Dioxus and Tauri tests in a single WDIO session (not recommended for most cases), both services can coexist in the same config: ``` export const config = { specs: ['./test/**/*.spec.ts'], services: [ ['@wdio/dioxus-service', { driverProvider: 'embedded' }], ['@wdio/tauri-service', { driverProvider: 'embedded' }], ], capabilities: [ { browserName: 'dioxus', 'dioxus:options': { application: './target/debug/my_dioxus_app', }, }, { browserName: 'tauri', 'tauri:options': { application: './src-tauri/target/debug/my_tauri_app', }, }, ], }; ``` Each service only activates for capabilities with a matching `browserName`. The Dioxus service ignores `tauri:options` capabilities and vice versa. ## Port Management[​](#port-management "Direct link to Port Management") If running multiple services simultaneously, ensure their embedded ports do not conflict: ``` services: [ ['@wdio/dioxus-service', { driverProvider: 'embedded', embeddedPort: 4445 }], ['@wdio/tauri-service', { driverProvider: 'embedded', embeddedPort: 4450 }], ], ``` ## CI Matrix[​](#ci-matrix "Direct link to CI Matrix") For CI, test each framework in parallel across OS runners: ``` # .github/workflows/e2e.yml jobs: e2e-dioxus: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' - uses: dtolnay/rust-toolchain@stable - name: Install Linux dependencies if: runner.os == 'Linux' run: sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev - run: npm install - run: cargo build working-directory: apps/dioxus-app - name: Run tests (Linux needs a virtual display) if: runner.os == 'Linux' run: xvfb-run -a npm run test:e2e:dioxus - name: Run tests if: runner.os != 'Linux' run: npm run test:e2e:dioxus e2e-tauri: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' - uses: dtolnay/rust-toolchain@stable - name: Install Linux dependencies if: runner.os == 'Linux' run: sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev - run: npm install - run: cargo build working-directory: apps/tauri-app/src-tauri - name: Run tests (Linux needs a virtual display) if: runner.os == 'Linux' run: xvfb-run -a npm run test:e2e:tauri - name: Run tests if: runner.os != 'Linux' run: npm run test:e2e:tauri e2e-electron: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' - run: npm install - run: npm run build:electron-app - name: Run tests (Linux needs a virtual display) if: runner.os == 'Linux' run: xvfb-run -a npm run test:e2e:electron - name: Run tests if: runner.os != 'Linux' run: npm run test:e2e:electron ``` ## See Also[​](#see-also "Direct link to See Also") * [@wdio/tauri-service README](https://github.com/webdriverio/desktop-mobile/blob/34f791f7984e1a32e816251f318ee64e48c23cf6/packages/tauri-service/README.md) * [@wdio/electron-service README](https://github.com/webdriverio/desktop-mobile/blob/34f791f7984e1a32e816251f318ee64e48c23cf6/packages/electron-service/README.md) * [Configuration](/docs/desktop-testing/dioxus/configuration.md) * [Platform Support](/docs/desktop-testing/dioxus/platform-support.md) --- Source: https://webdriver.io/docs/desktop-testing/dioxus/troubleshooting.md # Troubleshooting Solutions for common issues when testing Dioxus applications with WebdriverIO. ## Bridge Issues[​](#bridge-issues "Direct link to Bridge Issues") ### "Bridge not available" or execute always returns undefined[​](#bridge-not-available-or-execute-always-returns-undefined "Direct link to \"Bridge not available\" or execute always returns undefined") The `wdio-dioxus-bridge` crate is not wired into your app. **Check 1: Bridge crate in dependencies** ``` # Cargo.toml [dependencies] wdio-dioxus-bridge = "1" ``` **Check 2: Bridge installed in `main.rs`** ``` fn main() { let mut config = dioxus::desktop::Config::new(); #[cfg(debug_assertions)] { config = wdio_dioxus_bridge::install(config); } dioxus::LaunchBuilder::desktop().with_cfg(config).launch(App); } ``` **Check 3: Debug build used for testing** The bridge is only compiled in debug builds. Ensure you are using `cargo build` (not `cargo build --release`) and the binary path in your config points to `target/debug/my_app`, not `target/release/my_app`. **Check 4: Rebuild application** ``` cargo clean cargo build ``` See [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md) for the complete installation guide. ## Driver Installation Issues[​](#driver-installation-issues "Direct link to Driver Installation Issues") ### "wdio-dioxus-driver not found" (`'external'` provider, Windows)[​](#wdio-dioxus-driver-not-found-external-provider-windows "Direct link to wdio-dioxus-driver-not-found-external-provider-windows") The service cannot find the wdio-dioxus-driver executable. **Solution 1: Enable Auto-Installation** ``` services: [['@wdio/dioxus-service', { driverProvider: 'external', autoInstallDioxusDriver: true, }]] ``` **Solution 2: Manual Installation** ``` cargo install wdio-dioxus-driver ``` **Solution 3: Specify Path Manually** ``` services: [['@wdio/dioxus-service', { driverProvider: 'external', dioxusDriverPath: '/custom/path/wdio-dioxus-driver', }]] ``` ### "MSEdgeDriver not found" (Windows, `'external'` provider)[​](#msedgedriver-not-found-windows-external-provider "Direct link to msedgedriver-not-found-windows-external-provider") **Solution 1: Enable Auto-Download** ``` services: [['@wdio/dioxus-service', { driverProvider: 'external', autoDownloadEdgeDriver: true, // Default: true }]] ``` **Solution 2: Manual Download** 1. Check your WebView2 version (right-click your binary → Properties → Details) 2. Download matching MSEdgeDriver from [Microsoft Edge WebDriver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) 3. Add to PATH See [Edge WebDriver (Windows)](/docs/desktop-testing/dioxus/edge-webdriver-windows.md) for detailed setup. ## Provider Issues[​](#provider-issues "Direct link to Provider Issues") ### "external provider not supported on Linux"[​](#external-provider-not-supported-on-linux "Direct link to \"external provider not supported on Linux\"") `'external'` is blocked on Linux in v1 — an upstream Dioxus PR is pending. Use `driverProvider: 'embedded'` instead. ``` services: [['@wdio/dioxus-service', { driverProvider: 'embedded', // The only supported option on Linux }]] ``` ### "external provider not supported on macOS"[​](#external-provider-not-supported-on-macos "Direct link to \"external provider not supported on macOS\"") `'external'` is not supported on macOS. Use `driverProvider: 'embedded'`. ### "No driverProvider configured" or service fails to start[​](#no-driverprovider-configured-or-service-fails-to-start "Direct link to \"No driverProvider configured\" or service fails to start") Set `driverProvider` explicitly: ``` services: [['@wdio/dioxus-service', { driverProvider: 'embedded', // Recommended everywhere }]] ``` ## Application Issues[​](#application-issues "Direct link to Application Issues") ### "Application not found at path"[​](#application-not-found-at-path "Direct link to \"Application not found at path\"") The Dioxus app binary cannot be found. **Solution 1: Verify Binary Exists** ``` ls -la target/debug/my_app # Linux/macOS dir target\debug\my_app.exe # Windows ``` **Solution 2: Build the Application** ``` cargo build # Debug build (bridge active) ``` **Solution 3: Use Correct Path** ``` services: [['@wdio/dioxus-service', { appBinaryPath: './target/debug/my_app', // Linux/macOS // or appBinaryPath: './target/debug/my_app.exe', // Windows }]] ``` **Solution 4: Use Absolute Path** ``` import path from 'path'; services: [['@wdio/dioxus-service', { appBinaryPath: path.resolve('./target/debug/my_app'), }]] ``` ### Debug vs. Release Build Mismatch[​](#debug-vs-release-build-mismatch "Direct link to Debug vs. Release Build Mismatch") The bridge is only compiled into debug builds. If you point `appBinaryPath` at a release binary, the bridge will not be present and `browser.dioxus.execute()` will fail. Always use `cargo build` (without `--release`) for testing. ### Commands Timing Out[​](#commands-timing-out "Direct link to Commands Timing Out") **Solution 1: Increase Start Timeout** ``` services: [['@wdio/dioxus-service', { startTimeout: 60000, // Allow more time for app to start }]] ``` **Solution 2: Increase Status Poll Timeout** For slow CI environments: ``` services: [['@wdio/dioxus-service', { statusPollTimeout: 5000, // Default: 2000 }]] ``` **Solution 3: Wait for App to Be Ready** ``` it('should wait for app', async () => { await browser.pause(1000); const element = await browser.$('button'); expect(element).toBeDefined(); }); ``` ### "Port already in use"[​](#port-already-in-use "Direct link to \"Port already in use\"") **Solution 1: Change Embedded Port** ``` services: [['@wdio/dioxus-service', { embeddedPort: 4446, // Instead of default 4445 }]] ``` **Solution 2: Kill Process Using Port** ``` # Linux/macOS lsof -ti:4445 | xargs kill -9 # Windows (PowerShell) Get-Process -Id (Get-NetTCPConnection -LocalPort 4445).OwningProcess | Stop-Process -Force ``` ## Mocking Issues[​](#mocking-issues "Direct link to Mocking Issues") ### Mocking Doesn't Work[​](#mocking-doesnt-work "Direct link to Mocking Doesn't Work") **Check 1: Mock Set Up Before Call** ``` // Correct — mock first, then call const mock = await browser.dioxus.mock('my_command'); await mock.mockReturnValue('test'); await browser.dioxus.execute(({ invoke }) => invoke('my_command')); // Wrong — calling before mocking await browser.dioxus.execute(({ invoke }) => invoke('my_command')); const mock = await browser.dioxus.mock('my_command'); ``` **Check 2: Correct Command Name** ``` // Command name must match exactly what your app passes to invoke() const mock = await browser.dioxus.mock('get_user'); await mock.mockReturnValue({ id: 1 }); ``` ## Multi-Window Issues[​](#multi-window-issues "Direct link to Multi-Window Issues") ### Window Label Not Found[​](#window-label-not-found "Direct link to Window Label Not Found") **Error:** `Window label "settings" not found. Available windows: main` **Solution:** ``` // Debug: list available windows const windows = await browser.dioxus.listWindows(); console.log('Available:', windows); ``` Verify the window label matches exactly (case-sensitive) and the window is created before your test runs. ## Linux Headless Issues[​](#linux-headless-issues "Direct link to Linux Headless Issues") ### "X11 connection refused" or "Cannot open display"[​](#x11-connection-refused-or-cannot-open-display "Direct link to \"X11 connection refused\" or \"Cannot open display\"") ``` # Install Xvfb sudo apt-get install -y xvfb # Run tests headless xvfb-run -a npx wdio run wdio.conf.ts ``` ## CI/CD Issues[​](#cicd-issues "Direct link to CI/CD Issues") ### Tests Fail in CI But Pass Locally[​](#tests-fail-in-ci-but-pass-locally "Direct link to Tests Fail in CI But Pass Locally") **Common Causes:** 1. **Missing Linux build dependencies** ``` sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev ``` 2. **Display server missing on Linux CI** ``` xvfb-run -a npm run test:e2e ``` 3. **Release binary used instead of debug** * Ensure `cargo build` (not `cargo build --release`) is run in CI * Verify the binary path in `wdio.conf.ts` points to `target/debug/`, not `target/release/` 4. **Environment Variables** ``` APP_BINARY="./target/debug/my_app" npm run test:e2e ``` ## Debug Mode[​](#debug-mode "Direct link to Debug Mode") ### Enable Debug Logging[​](#enable-debug-logging "Direct link to Enable Debug Logging") ``` services: [['@wdio/dioxus-service', { captureBackendLogs: true, captureFrontendLogs: true, }]] ``` ### Verbose Test Output[​](#verbose-test-output "Direct link to Verbose Test Output") ``` npx wdio run wdio.conf.ts --logLevel debug ``` ## Getting Help[​](#getting-help "Direct link to Getting Help") If you're still stuck: 1. **Check [Configuration](/docs/desktop-testing/dioxus/configuration.md)** for all available options 2. **Review [Usage Examples](/docs/desktop-testing/dioxus/usage-examples.md)** for correct patterns 3. **See [Bridge Setup](/docs/desktop-testing/dioxus/plugin-setup.md)** for bridge requirements 4. **Check [Platform Support](/docs/desktop-testing/dioxus/platform-support.md)** for platform-specific issues 5. **Enable debug logging** to see detailed output 6. **Open a discussion** in the [GitHub Discussions](https://github.com/webdriverio/desktop-mobile/discussions) --- Source: https://webdriver.io/docs/platforms/apps-and-extensions.md # Extensions & Editors WebdriverIO tests browser extensions and editor extensions by loading them into the real host application. Browser (web) extensions run inside Chrome or Firefox. You load them through browser capabilities: `--load-extension` or a base64 `.crx` via `goog:chromeOptions` in Chrome, or `browser.installAddOn()` for an `.xpi` in Firefox. In a WebDriver BiDi session you can also install and remove an extension mid-session with `browser.installExtension()` and `browser.uninstallExtension()`. Safari has no BiDi session, so that command does not cover Safari. From there, you test content scripts and popup pages with the normal WebDriver commands. VS Code extensions are tested with the community [`wdio-vscode-service`](/docs/wdio-vscode-service.md). It downloads VS Code (stable, insiders or a specific version) and the matching Chromedriver, then starts VS Code with your extension and custom user settings. Page objects for the workbench are available through `browser.getWorkbench()`, and `browser.executeWorkbench()` runs code against the VS Code API. The same service can also serve VS Code in a browser to test web extensions. Obsidian plugins have a community service too. ## Quick start[​](#quick-start "Direct link to Quick start") Install the testrunner and TypeScript support first: ``` npm install --save-dev @wdio/cli @wdio/local-runner @wdio/mocha-framework @wdio/spec-reporter tsx ``` tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types", "@wdio/mocha-framework"] } } ``` ### Chrome extension[​](#chrome-extension "Direct link to Chrome extension") Build your extension into a folder (here `./dist`) and load it with the `--load-extension` Chrome argument: wdio.conf.ts ``` import path from 'node:path' import url from 'node:url' const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) export const config: WebdriverIO.Config = { runner: 'local', specs: ['./test/specs/**/*.ts'], capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { args: [`--load-extension=${path.join(__dirname, 'dist')}`] } }], framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', timeout: 60000 } } ``` test/specs/extension.e2e.ts ``` import { expect, browser, $ } from '@wdio/globals' describe('My Web Extension', () => { it('should inject its content script', async () => { await browser.url('https://webdriver.io') // replace with an element your content script adds to the page await expect($('#my-extension-root')).toBeExisting() }) }) ``` Clicking the extension icon in the toolbar doesn't work. To test a `default_popup`, find the extension id on `chrome://extensions/` and open `chrome-extension:///.html` with `browser.url()`. The [Web Extension guide](/docs/extension-testing/web-extensions.md#test-popup-modal-in-chrome) has a ready-made `openExtensionPopup` custom command for this. ### VS Code extension[​](#vs-code-extension "Direct link to VS Code extension") ``` npm install --save-dev wdio-vscode-service ``` Add `"wdio-vscode-service"` to the `types` array in `tsconfig.json`. wdio.conf.ts ``` import url from 'node:url' const __dirname = url.fileURLToPath(new URL('.', import.meta.url)) export const config: WebdriverIO.Config = { runner: 'local', specs: ['./test/specs/**/*.ts'], capabilities: [{ browserName: 'vscode', browserVersion: 'stable', // also possible: "insiders" or a specific version e.g. "1.80.0" 'wdio:vscodeOptions': { // points to directory where extension package.json is located extensionPath: __dirname, userSettings: { 'editor.fontSize': 14 } } }], services: ['vscode'], framework: 'mocha', reporters: ['spec'], mochaOpts: { ui: 'bdd', timeout: 60000 } } ``` test/specs/vscode.e2e.ts ``` import { browser, expect } from '@wdio/globals' describe('VS Code Extension Testing', () => { it('should be able to load VSCode', async () => { const workbench = await browser.getWorkbench() expect(await workbench.getTitleBar().getTitle()) .toContain('[Extension Development Host]') }) }) ``` To test the extension as a VS Code web extension, set `browserName: 'chrome'` and keep `wdio:vscodeOptions`. In that mode, `browserVersion` can only be `stable` or `insiders`. `npm create wdio@latest ./` with "VS Code Extension Testing" generates this setup for you. ## Choose your path[​](#choose-your-path "Direct link to Choose your path") * [Web Extension Testing](/docs/extension-testing/web-extensions.md): load extensions in Chrome (folder or `.crx`) and Firefox (`.xpi` via [`installAddOn`](/docs/api/gecko.md#installaddon)), or install and remove one mid-session with [`installExtension`](/docs/api/browser/installExtension.md). Safari web extensions are not covered. * [Firefox Profile Service](/docs/firefox-profile-service.md): build a Firefox profile that includes extensions. * [VS Code Extension Testing](/docs/extension-testing/vscode-extensions.md): configuration, TypeScript setup, workbench page objects and `executeWorkbench`. * [VS Code Service](/docs/wdio-vscode-service.md): all service options, such as `cachePath`, and how to write custom page objects. * [Obsidian Plugin Testing Service](/docs/wdio-obsidian-service.md): a community service that tests Obsidian plugins across Obsidian versions on Windows, macOS, Linux and Android. * [Custom Commands](/docs/customcommands.md): package helpers like `openExtensionPopup` for reuse. Web extension tests run in a regular Chrome or Firefox session, so everything on [Web Browsers](/docs/platforms/web.md) applies, including selectors, network mocking and visual testing. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") * Firefox refuses a locally built extension because of signing: install it in the `before` hook with `browser.installAddOn(extension.toString('base64'), true)` instead of through a profile. Build the `.xpi` with `npx web-ext build`. * Using Edge, Brave or Opera instead of Chrome: the same arguments usually work with that browser's options capability, e.g. `ms:edgeOptions`. * VS Code and Chromedriver binaries are downloaded into a cache directory. To control where they are stored, e.g. to cache them in CI, set `services: [['vscode', { cachePath: __dirname }]]`. * TypeScript can't find `getWorkbench` or `executeWorkbench`: add `wdio-vscode-service` to `compilerOptions.types`. ## Next steps[​](#next-steps "Direct link to Next steps") * [Configuration](/docs/configuration.md) reference for every `wdio.conf.ts` option. * [Electron](/docs/desktop-testing/electron.md) for testing full desktop apps built on Chromium. * Other platforms: [Web Browsers](/docs/platforms/web.md), [Mobile Apps](/docs/platforms/mobile.md), [Desktop Apps](/docs/platforms/desktop.md). --- Source: https://webdriver.io/docs/extension-testing/vscode-extensions.md # VS Code Extension Testing WebdriverIO allows you to seamlessly test your [VS Code](https://code.visualstudio.com/) extensions from end to end in the VS Code Desktop IDE or as web extension. You only need to provide a path to your extension and the framework does the rest. With the [`wdio-vscode-service`](https://www.npmjs.com/package/wdio-vscode-service) everything is taken care of and much more: * 🏗️ Installing VSCode (either stable, insiders or a specified version) * ⬇️ Downloading Chromedriver specific to given VSCode version * 🚀 Enables you to access the VSCode API from your tests * 🖥️ Starting VSCode with custom user settings (including support for VSCode on Ubuntu, MacOS and Windows) * 🌐 Or serves VSCode from a server to be accessed by any browser for testing web extensions * 📔 Bootstrapping page objects with locators matching your VSCode version ## Getting Started[​](#getting-started "Direct link to Getting Started") To initiate a new WebdriverIO project, run: ``` npm create wdio@latest ./ ``` An installation wizard will guide you through the process. Ensure you select *"VS Code Extension Testing"* when it asks you what type of testing you'ld like to do, afterwards just keep the defaults or modify based on your preference. ## Example Configuration[​](#example-configuration "Direct link to Example Configuration") To use the service you need to add `vscode` to your list of services, optionally followed by a configuration object. This will make WebdriverIO download given VSCode binaries and appropiate Chromedriver version: ``` // wdio.conf.ts export const config = { outputDir: 'trace', // ... capabilities: [{ browserName: 'vscode', browserVersion: '1.71.0', // "insiders" or "stable" for latest VSCode version 'wdio:vscodeOptions': { extensionPath: __dirname, userSettings: { "editor.fontSize": 14 } } }], services: ['vscode'], /** * optionally you can define the path WebdriverIO stores all * VSCode and Chromedriver binaries, e.g.: * services: [['vscode', { cachePath: __dirname }]] */ // ... }; ``` If you define `wdio:vscodeOptions` with any other `browserName` but `vscode`, e.g. `chrome`, the service will serve the extension as web extension. If you test on Chrome no additional driver service is required, e.g.: ``` // wdio.conf.ts export const config = { outputDir: 'trace', // ... capabilities: [{ browserName: 'chrome', 'wdio:vscodeOptions': { extensionPath: __dirname } }], services: ['vscode'], // ... }; ``` *Note:* when testing web extensions you can only choose between `stable` or `insiders` as `browserVersion`. ### TypeScript Setup[​](#typescript-setup "Direct link to TypeScript Setup") In your `tsconfig.json` make sure to add `wdio-vscode-service` to your list of types: ``` { "compilerOptions": { "types": [ "node", "webdriverio/async", "@wdio/mocha-framework", "expect-webdriverio", "wdio-vscode-service" ], "target": "es2020", "moduleResolution": "node16" } } ``` ## Usage[​](#usage "Direct link to Usage") You can then use the `getWorkbench` method to access the page objects for the locators matching your desired VSCode version: ``` describe('WDIO VSCode Service', () => { it('should be able to load VSCode', async () => { const workbench = await browser.getWorkbench() expect(await workbench.getTitleBar().getTitle()) .toBe('[Extension Development Host] - README.md - wdio-vscode-service - Visual Studio Code') }) }) ``` From there you can access all page objects by using the right page object methods. Find out more about all available page objects and their methods in the [page object docs](https://webdriverio-community.github.io/wdio-vscode-service/). ### Accessing VSCode APIs[​](#accessing-vscode-apis "Direct link to Accessing VSCode APIs") If you like to execute certain automation through the [VSCode API](https://code.visualstudio.com/api/references/vscode-api) you can do that by running remote commands via the custom `executeWorkbench` command. This command allows to remote execute code from your test inside the VSCode environment and enables to access the VSCode API. You can pass arbitrary paramaters into the function which will then be propagated into the function. The `vscode` object will be always passed in as first argument following the outer function parameters. Note that you can not access variables outside of the function scoped as the callback is executed remotely. Here is an example: ``` const workbench = await browser.getWorkbench() await browser.executeWorkbench((vscode, param1, param2) => { vscode.window.showInformationMessage(`I am an ${param1} ${param2}!`) }, 'API', 'call') const notifs = await workbench.getNotifications() console.log(await notifs[0].getMessage()) // outputs: "I am an API call!" ``` For the full page object documentation, check out the [docs](https://webdriverio-community.github.io/wdio-vscode-service/modules.html). You can find various usage examples in this [project's test suite](https://github.com/webdriverio-community/wdio-vscode-service/blob/main/test/specs). ## More Information[​](#more-information "Direct link to More Information") You can learn more about how to configure the [`wdio-vscode-service`](https://www.npmjs.com/package/wdio-vscode-service) and how create custom page objects in the [service docs](/docs/wdio-vscode-service.md). You can also watch the following talk by [Christian Bromann](https://twitter.com/bromann) on [*Testing Complex VSCode Extensions With the Power of Web Standards*](https://www.youtube.com/watch?v=PhGNTioBUiU):