# 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\<ReturnValue>`

**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\<TauriMock>`

**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<void>`

**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<void>`

***

### `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<void>`

**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<void>`

**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<void>`

**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<string[]>`

**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\<TauriMock>`

**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\<TauriMock>`

***

### `mockReturnValue(value)`[​](#mockreturnvaluevalue "Direct link to mockreturnvaluevalue")

Set the mock to always return a specific value.

**Returns:** `Promise\<TauriMock>`

**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\<TauriMock>`

**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\<TauriMock>`

***

### `mockResolvedValueOnce(value)`[​](#mockresolvedvalueoncevalue "Direct link to mockresolvedvalueoncevalue")

Set the mock to resolve to a value for the next call only.

**Returns:** `Promise\<TauriMock>`

***

### `mockRejectedValue(error)`[​](#mockrejectedvalueerror "Direct link to mockrejectedvalueerror")

Set the mock to return a promise that rejects with an error.

**Returns:** `Promise\<TauriMock>`

**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\<TauriMock>`

***

### `mockClear()`[​](#mockclear "Direct link to mockclear")

Clear the call history of this mock without resetting its implementation.

**Returns:** `Promise\<TauriMock>`

***

### `mockReset()`[​](#mockreset "Direct link to mockreset")

Reset the mock to its initial state (clears both implementation and call history).

**Returns:** `Promise\<TauriMock>`

***

### `mockRestore()`[​](#mockrestore "Direct link to mockrestore")

Remove this mock and restore the original command implementation.

**Returns:** `Promise\<TauriMock>`

***

### `mockReturnThis()`[​](#mockreturnthis "Direct link to mockreturnthis")

Set the mock to return `this` when called (useful for chaining).

**Returns:** `Promise\<TauriMock>`

***

### `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\<TauriMock>`

***

### `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\<TauriAppInfo>`

**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<string>`

**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\<Browser>`

**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<void>`

***

### `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\<TauriServiceOptions>) - 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<string, string>;
  autoInstallTauriDriver?: boolean;
  autoDownloadEdgeDriver?: boolean;
  logDir?: string;
}
```

### `TauriServiceGlobalOptions`[​](#tauriserviceglobaloptions "Direct link to tauriserviceglobaloptions")

Global options passed at the service level (not per-capability).

### `TauriResult<T>`[​](#tauriresultt "Direct link to tauriresultt")

Uses the standard Result pattern:

```
type TauriResult<T = unknown> = { 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).
