# Configuration

Based on the [setup type](/docs/setuptypes.md) (e.g. using the raw protocol bindings, WebdriverIO as standalone package or the WDIO testrunner) there is a different set of options available to control the environment.

## WebDriver Options[​](#webdriver-options "Direct link to WebDriver Options")

The following options are defined when using the [`webdriver`](https://www.npmjs.com/package/webdriver) protocol package:

### protocol[​](#protocol "Direct link to protocol")

* Type

  `String`

* Default

  `http`

Protocol to use when communicating with the driver server.

### hostname[​](#hostname "Direct link to hostname")

* Type

  `String`

* Default

  `0.0.0.0`

Host of your driver server.

### port[​](#port "Direct link to port")

* Type

  `Number`

* Default

  `undefined`

Port your driver server is on.

### path[​](#path "Direct link to path")

* Type

  `String`

* Default

  `/`

Path to driver server endpoint.

### queryParams[​](#queryparams "Direct link to queryParams")

* Type

  `Object`

* Default

  `undefined`

Query parameters that are propagated to the driver server.

### user[​](#user "Direct link to user")

* Type

  `String`

* Default

  `undefined`

Your cloud service username (only works for [Sauce Labs](https://saucelabs.com), [Browserstack](https://www.browserstack.com), [TestingBot](https://testingbot.com) or [TestMu AI](https://www.testmuai.com/) accounts). If set, WebdriverIO will automatically set connection options for you. If you don't use a cloud provider this can be used to authenticate any other WebDriver backend.

### key[​](#key "Direct link to key")

* Type

  `String`

* Default

  `undefined`

Your cloud service access key or secret key (only works for [Sauce Labs](https://saucelabs.com), [Browserstack](https://www.browserstack.com), [TestingBot](https://testingbot.com) or [TestMu AI](https://www.testmuai.com/) accounts). If set, WebdriverIO will automatically set connection options for you. If you don't use a cloud provider this can be used to authenticate any other WebDriver backend.

### capabilities[​](#capabilities "Direct link to capabilities")

* Type

  `Object`

* Default

  `null`

Defines the capabilities you want to run in your WebDriver session. Check out the [WebDriver Protocol](https://w3c.github.io/webdriver/#capabilities) for more details.

Next to the WebDriver based capabilities you can apply browser and vendor specific options that allow deeper configuration to the remote browser or device. These are documented in the corresponding vendor docs, e.g.:

* `goog:chromeOptions`: for [Google Chrome](https://chromedriver.chromium.org/capabilities#h.p_ID_106)
* `moz:firefoxOptions`: for [Mozilla Firefox](https://firefox-source-docs.mozilla.org/testing/geckodriver/Capabilities.html)
* `ms:edgeOptions`: for [Microsoft Edge](https://docs.microsoft.com/en-us/microsoft-edge/webdriver-chromium/capabilities-edge-options#using-the-edgeoptions-class)
* `sauce:options`: for [Sauce Labs](https://docs.saucelabs.com/dev/test-configuration-options/#desktop-and-mobile-capabilities-sauce-specific--optional)
* `bstack:options`: for [BrowserStack](https://www.browserstack.com/automate/capabilities?tag=selenium-4#)
* `selenoid:options`: for [Selenoid](https://github.com/aerokube/selenoid/blob/master/docs/special-capabilities.adoc)

Additionally, a useful utility is the Sauce Labs [Automated Test Configurator](https://docs.saucelabs.com/basics/platform-configurator/), which helps you create this object by clicking together your desired capabilities.

**Example:**

```
{

    browserName: 'chrome', // options: `chrome`, `edge`, `firefox`, `safari`

    browserVersion: '27.0', // browser version

    platformName: 'Windows 10' // OS platform

}
```

If you’re running web or native tests on mobile devices, `capabilities` differs from the WebDriver protocol. See the [Appium Docs](https://appium.io/docs/en/latest/guides/caps/) for more details.

### logLevel[​](#loglevel "Direct link to logLevel")

* Type

  `String`

* Default

  `info`

* Values

  `trace | debug | info | warn | error | silent`

Level of logging verbosity.

### outputDir[​](#outputdir "Direct link to outputDir")

* Type

  `String`

* Default

  `null`

Directory to store all testrunner log files (including reporter logs and `wdio` logs). If not set, all logs are streamed to `stdout`. Since most reporters are made to log to `stdout`, it is recommended to only use this option for specific reporters where it makes more sense to push report into a file (like the `junit` reporter, for example).

When running in standalone mode, the only log generated by WebdriverIO will be the `wdio` log.

### connectionRetryTimeout[​](#connectionretrytimeout "Direct link to connectionRetryTimeout")

* Type

  `Number`

* Default

  `120000`

Timeout for any WebDriver request to a driver or grid.

### connectionRetryCount[​](#connectionretrycount "Direct link to connectionRetryCount")

* Type

  `Number`

* Default

  `3`

Maximum count of request retries to the Selenium server.

### bidiResponseTimeout[​](#bidiresponsetimeout "Direct link to bidiResponseTimeout")

* Type

  `Number`

* Default

  `180000`

Timeout (in ms) for a WebDriver Bidi command to receive a response from the browser. Increase this if you run commands, e.g. [`execute`](/docs/api/browser/execute.md), that legitimately take longer than the default to resolve, otherwise WebdriverIO gives up waiting before the browser is done.

`execute` also stops at the `script` timeout of the session (30 seconds by default, see [`setTimeout`](/docs/api/browser/setTimeout.md)). For a `script` timeout longer than `bidiResponseTimeout`, increase both.

### bidiConnectTimeout[​](#bidiconnecttimeout "Direct link to bidiConnectTimeout")

* Type

  `Number`

* Default

  `10000`

Timeout (in ms) for the browser to accept the WebDriver Bidi connection. After it, the session continues with WebDriver Classic, and Bidi-only commands such as [`mock`](/docs/api/browser/mock.md) fail. Increase it if a browser that is busy at startup, e.g. several browsers that start at the same time on a CI runner, accepts the connection late.

This option applies to sessions in Node.js. In a browser, for example with the [browser runner](/docs/runner.md#browser-runner), the connection waits until it opens or fails.

### agent[​](#agent "Direct link to agent")

* Type

  `Object`

* Default

  ```
  {
    http: new http.Agent({ keepAlive: true }),
    https: new https.Agent({ keepAlive: true })
  }
  ```

Allows you to use a custom` http`/`https`/`http2` [agent](https://www.npmjs.com/package/got#agent) to make requests.

### headers[​](#headers "Direct link to headers")

* Type

  `Object`

* Default

  `{}`

Specify custom `headers` to pass into every WebDriver request. If your Selenium Grid requires Basic Authentification we recommend to pass in an `Authorization` header through this option to authenticate your WebDriver requests, e.g.:

```
import { Buffer } from 'buffer';

// Read the username and password from environment variables

const username = process.env.SELENIUM_GRID_USERNAME;

const password = process.env.SELENIUM_GRID_PASSWORD;



// Combine the username and password with a colon separator

const credentials = `${username}:${password}`;

// Encode the credentials using Base64

const encodedCredentials = Buffer.from(credentials).toString('base64');



export const config: WebdriverIO.Config = {

    // ...

    headers: {

        Authorization: `Basic ${encodedCredentials}`

    }

    // ...

}
```

### transformRequest[​](#transformrequest "Direct link to transformRequest")

* Type

  `(RequestOptions) => RequestOptions`

* Default

  `none`

Function intercepting [HTTP request options](https://github.com/sindresorhus/got#options) before a WebDriver request is made

### transformResponse[​](#transformresponse "Direct link to transformResponse")

* Type

  `(Response, RequestOptions) => Response`

* Default

  `none`

Function intercepting HTTP response objects after a WebDriver response has arrived. The function is passed the original response object as the first and the corresponding `RequestOptions` as the second argument.

### strictSSL[​](#strictssl "Direct link to strictSSL")

* Type

  `Boolean`

* Default

  `true`

Whether it does not require SSL certificate to be valid. It can be set via an environment variables as `STRICT_SSL` or `strict_ssl`.

### enableDirectConnect[​](#enabledirectconnect "Direct link to enableDirectConnect")

* Type

  `Boolean`

* Default

  `true`

Whether enable [Appium direct connection feature](https://appiumpro.com/editions/86-connecting-directly-to-appium-hosts-in-distributed-environments). It does nothing if the response did not have proper keys while the flag is enabled.

### cacheDir[​](#cachedir "Direct link to cacheDir")

* Type

  `String`

* Default

  `process.env.WEBDRIVER_CACHE_DIR || os.tmpdir()`

The path to the root of the cache directory. This directory is used to store all drivers that are downloaded when attempting to start a session.

### maskingPatterns[​](#maskingpatterns "Direct link to maskingPatterns")

* Type

  `String`

* Default

  `undefined`

For more secure logging, regular expressions set with `maskingPatterns` can obfuscate sensitive information from the log.

* The string format is a regular expression with or without flags (e.g. `/.../i`) and comma-separated for multiple regular expressions.
* For more details on masking patterns, see the [Masking Patterns section in the WDIO Logger README](https://github.com/webdriverio/webdriverio/blob/main/packages/wdio-logger/README.md#masking-patterns).

**Example:**

```
{

    maskingPatterns: '/--key=([^ ]*)/i,/RESULT (.*)/'

}
```

## WebdriverIO[​](#webdriverio "Direct link to WebdriverIO")

The following options (including the ones listed above) can be used with WebdriverIO in standalone:

### automationProtocol[​](#automationprotocol "Direct link to automationProtocol")

* Type

  `String`

* Default

  `webdriver`

Define the protocol you want to use for your browser automation. Currently only [`webdriver`](https://www.npmjs.com/package/webdriver) is supported, as it is the main browser automation technology WebdriverIO uses.

If you want to automate the browser using a different automation technology, make you set this property to a path that resolves to a module that adheres to the following interface:

```
import type { Capabilities } from '@wdio/types';

import type { Client, AttachOptions } from 'webdriver';



export default class YourAutomationLibrary {

    /**

     * Start a automation session and return a WebdriverIO [monad](https://github.com/webdriverio/webdriverio/blob/940cd30939864bdbdacb2e94ee6e8ada9b1cc74c/packages/wdio-utils/src/monad.ts)

     * with respective automation commands. See the [webdriver](https://www.npmjs.com/package/webdriver) package

     * as a reference implementation

     *

     * @param {Capabilities.RemoteConfig} options WebdriverIO options

     * @param {Function} hook that allows to modify the client before it gets released from the function

     * @param {PropertyDescriptorMap} userPrototype allows user to add custom protocol commands

     * @param {Function} customCommandWrapper allows to modify the command execution

     * @returns a WebdriverIO compatible client instance

     */

    static newSession(

        options: Capabilities.RemoteConfig,

        modifier?: (...args: any[]) => any,

        userPrototype?: PropertyDescriptorMap,

        customCommandWrapper?: (...args: any[]) => any

    ): Promise<Client>;



    /**

     * allows user to attach to existing sessions

     * @optional

     */

    static attachToSession(

        options?: AttachOptions,

        modifier?: (...args: any[]) => any, userPrototype?: {},

        commandWrapper?: (...args: any[]) => any

    ): Client;



    /**

     * Changes The instance session id and browser capabilities for the new session

     * directly into the passed in browser object

     *

     * @optional

     * @param   {object} instance  the object we get from a new browser session.

     * @returns {string}           the new session id of the browser

     */

    static reloadSession(

        instance: Client,

        newCapabilities?: WebdriverIO.Capabilitie

    ): Promise<string>;

}
```

### baseUrl[​](#baseurl "Direct link to baseUrl")

* Type

  `String`

* Default

  `null`

Shorten `url` command calls by setting a base URL.

* If your `url` parameter starts with `/`, then `baseUrl` is prepended (except the `baseUrl` path, if it has one).
* If your `url` parameter starts without a scheme or `/` (like `some/path`), then the full `baseUrl` is prepended directly.

### waitforTimeout[​](#waitfortimeout "Direct link to waitforTimeout")

* Type

  `Number`

* Default

  `5000`

Default timeout for all `waitFor*` commands. (Note the lowercase `f` in the option name.) This timeout **only** affects commands starting with `waitFor*` and their default wait time.

To increase the timeout for a *test*, please see the framework docs.

### waitforInterval[​](#waitforinterval "Direct link to waitforInterval")

* Type

  `Number`

* Default

  `100`

Default interval for all `waitFor*` commands to check if an expected state (e.g., visibility) has been changed.

### strictSelectors[​](#strictselectors "Direct link to strictSelectors")

* Type

  `Boolean`

* Default

  `true`

Makes the [`$`](/docs/api/browser/$.md) command throw a `StrictSelectorError` when the given selector resolves to more than one element, instead of silently using the first match. `$$` is unaffected.

You can opt out for a single query by passing `{ strict: false }` as second argument, e.g. `$('button', { strict: false })`.

See the [Selectors](/docs/selectors.md#strict-mode) guide for details.

### maxSpyCollectedBodySize[​](#maxspycollectedbodysize "Direct link to maxSpyCollectedBodySize")

* Type

  `Number`

* Default

  `10485760 (10MB)`

Maximum size of the response body (in bytes) that can be returned when using the [`mock`](/docs/api/browser/mock.md) command. Use `0` to disable data collection of the spied payload.

### region[​](#region "Direct link to region")

* Type

  `String`

* Default

  `us`

* Values

  `us | eu | us-west-1 | eu-central-1 | us-east-4 | asia-south-2 | staging`

If running on Sauce Labs, you can choose to run tests between different data centers. Use short region handles `us` (default, maps to `us-west-1`) or `eu` (maps to `eu-central-1`), or the full region names directly.

**Note:** This only has an effect if you provide `user` and `key` options that are connected to your Sauce Labs account.

*(only for vm and or em/simulators, except `us-east-4` and `asia-south-2` which host real devices only)*

## Testrunner Options[​](#testrunner-options "Direct link to Testrunner Options")

The following options (including the ones listed above) are defined only for running WebdriverIO with the WDIO testrunner:

### specs[​](#specs "Direct link to specs")

* Type

  `(String | String[])[]`

* Default

  `[]`

Define specs for test execution. You can either specify a glob pattern to match multiple files at once or wrap a glob or set of paths into an array to run them within a single worker process. All paths are seen as relative from the config file path.

### exclude[​](#exclude "Direct link to exclude")

* Type

  `String[]`

* Default

  `[]`

Exclude specs from test execution. All paths are seen as relative from the config file path.

### suites[​](#suites "Direct link to suites")

* Type

  `Object`

* Default

  `{}`

An object describing various suites, which you can then specify with the `--suite` option on the `wdio` CLI.

### capabilities[​](#capabilities-1 "Direct link to capabilities")

* Type

  `Object|Object[]`

* Default

  `[{ 'wdio:maxInstances': 5, browserName: 'firefox' }]`

The same as the `capabilities` section described above, except with the option to specify either a [multi-remote](/docs/multiremote.md) object, or multiple WebDriver sessions in an array for parallel execution.

You can apply the same vendor and browser specific capabilities as defined [above](/docs/configuration.md#capabilities).

### maxInstances[​](#maxinstances "Direct link to maxInstances")

* Type

  `Number`

* Default

  `100`

Maximum number of total parallel running workers.

**Note:** that it may be a number as high as `100`, when the tests are being performed on some external vendors such as Sauce Labs's machines. There, the tests are not tested on a single machine, but rather, on multiple VMs. If the tests are to be run on a local development machine, use a number that is more reasonable, such as `3`, `4`, or `5`. Essentially, this is the number of browsers that will be concurrently started and running your tests at the same time, so it depends on how much RAM there is on your machine, and how many other apps are running on your machine.

You can also apply `maxInstances` within your capability objects using the `wdio:maxInstances` capability. This will limit the amount of parallel sessions for that particular capability.

### maxInstancesPerCapability[​](#maxinstancespercapability "Direct link to maxInstancesPerCapability")

* Type

  `Number`

* Default

  `100`

Maximum number of total parallel running workers per capability.

### injectGlobals[​](#injectglobals "Direct link to injectGlobals")

* Type

  `Boolean`

* Default

  `true`

Inserts WebdriverIO's globals (e.g. `browser`, `$` and `$$`) into the global environment. If you set to `false`, you should import from `@wdio/globals`, e.g.:

```
import { browser, $, $$, expect } from '@wdio/globals'
```

Note: WebdriverIO doesn't handle injection of test framework specific globals.

### bail[​](#bail "Direct link to bail")

* Type

  `Number`

* Default

  `0 (don't bail; run all tests)`

If you want your test run to stop after a specific number of test failures, use `bail`. (It defaults to `0`, which runs all tests no matter what.) **Note:** A test in this context are all tests within a single spec file (when using Mocha or Jasmine) or all steps within a feature file (when using Cucumber). If you want to control the bail behavior within tests of a single test file, take a look at the available [framework](/docs/frameworks.md) options.

### specFileRetries[​](#specfileretries "Direct link to specFileRetries")

* Type

  `Number`

* Default

  `0`

The number of times to retry an entire specfile when it fails as a whole.

### specFileRetriesDelay[​](#specfileretriesdelay "Direct link to specFileRetriesDelay")

* Type

  `Number`

* Default

  `0`

Delay in seconds between the spec file retry attempts

### specFileRetriesDeferred[​](#specfileretriesdeferred "Direct link to specFileRetriesDeferred")

* Type

  `Boolean`

* Default

  `true`

Whether or not retried spec files should be retried immediately or deferred to the end of the queue.

### groupLogsByTestSpec[​](#grouplogsbytestspec "Direct link to groupLogsByTestSpec")

* Type

  `Boolean`

* Default

  `false`

Choose the log output view.

If set to `false` logs from different test files will be printed in real-time. Please note that this may result in the mixing of log outputs from different files when running in parallel.

If set to `true` log outputs will be grouped by Test Spec and printed only when the Test Spec is completed.

By default, it is set to `false` so logs are printed in real-time.

### autoAssertOnTestEnd[​](#autoassertontestend "Direct link to autoAssertOnTestEnd")

* Type

  `Boolean`

* Default

  `true`

Controls whether WebdriverIO automatically asserts all soft assertions at the end of each test. When set to `true`, any accumulated soft assertions will be automatically checked and cause the test to fail if any assertions failed. When set to `false`, you must manually call the assert method to check soft assertions.

### services[​](#services "Direct link to services")

* Type

  `String[]|Object[]`

* Default

  `[]`

Services take over a specific job you don't want to take care of. They enhance your test setup with almost no effort.

### framework[​](#framework "Direct link to framework")

* Type

  `String`

* Default

  `mocha`

* Values

  `mocha | jasmine | cucumber`

Defines the test framework to be used by the WDIO testrunner.

### mochaOpts, jasmineOpts and cucumberOpts[​](#mochaopts-jasmineopts-and-cucumberopts "Direct link to mochaOpts, jasmineOpts and cucumberOpts")

* Type

  `Object`

* Default

  `{ timeout: 10000 }`

Specific framework-related options. See the framework adapter documentation on which options are available. Read more on this in [Frameworks](/docs/frameworks.md).

### cucumberFeaturesWithLineNumbers[​](#cucumberfeatureswithlinenumbers "Direct link to cucumberFeaturesWithLineNumbers")

* Type

  `String[]`

* Default

  `[]`

List of cucumber features with line numbers (when [using cucumber framework](/docs/frameworks.md#using-cucumber)).

### reporters[​](#reporters "Direct link to reporters")

* Type

  `String[]|Object[]`

* Default

  `[]`

List of reporters to use. A reporter can be either a string, or an array of `['reporterName', { /* reporter options */}]` where the first element is a string with the reporter name and the second element an object with reporter options.

Example:

```
reporters: [

    'dot',

    'spec'

    ['junit', {

        outputDir: `${__dirname}/reports`,

        otherOption: 'foobar'

    }]

]
```

### reporterSyncInterval[​](#reportersyncinterval "Direct link to reporterSyncInterval")

* Type

  `Number`

* Default

  `100 (ms)`

Determines in which interval the reporter should check if they are synchronized if they report their logs asynchronously (e.g. if logs are streamed to a 3rd party vendor).

### reporterSyncTimeout[​](#reportersynctimeout "Direct link to reporterSyncTimeout")

* Type

  `Number`

* Default

  `5000 (ms)`

Determines the maximum time reporters have to finish uploading all their logs until an error is being thrown by the testrunner.

### execArgv[​](#execargv "Direct link to execArgv")

* Type

  `String[]`

* Default

  `null`

Node arguments to specify when launching child processes.

### cpuProf[​](#cpuprof "Direct link to cpuProf")

* Type

  `Boolean`

* Default

  `false`

Enable CPU profiling for the worker process. The profile will be generated automatically when the worker process exits.

### heapProf[​](#heapprof "Direct link to heapProf")

* Type

  `Boolean`

* Default

  `false`

Enable Heap profiling for the worker process. The snapshot will be generated automatically when the worker process exits (uses sampling heap profiler).

### profileOutputDir[​](#profileoutputdir "Direct link to profileOutputDir")

* Type

  `String`

* Default

  `./profiles`

Directory where the CPU profiles (`.cpuprofile`) and Heap profiles (`.heapprofile`) will be saved.

### filesToWatch[​](#filestowatch "Direct link to filesToWatch")

* Type

  `String[]`

* Default

  `[]`

A list of glob supporting string patterns that tell the testrunner to have it additionally watch other files, e.g. application files, when running it with the `--watch` flag. By default the testrunner already watches all spec files.

### updateSnapshots[​](#updatesnapshots "Direct link to updateSnapshots")

* Type

  `'new' | 'all' | 'none'`

* Default

  `none if not provided and tests run in CI, new if not provided, otherwise what's been provided`

Set to true if you want to update your snapshots. Ideally used as part of a CLI parameter, e.g. `wdio run wdio.conf.js --s`.

### resolveSnapshotPath[​](#resolvesnapshotpath "Direct link to resolveSnapshotPath")

* Type

  `(testPath: string, snapExtension: string) => string`

* Default

  `stores snapshot files in __snapshots__ directory next to test file`

Overrides default snapshot path. For example, to store snapshots next to test files.

wdio.conf.ts

```
export const config: WebdriverIO.Config = {

    resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension,

}
```

### tsConfigPath[​](#tsconfigpath "Direct link to tsConfigPath")

* Type

  `String`

* Default

  `null`

WDIO uses `tsx` to compile TypeScript files. Your TSConfig is automatically detected from the current working directory but you can specify a custom path here or by setting the TSX\_TSCONFIG\_PATH environment variable.

See the `tsx` docs: <https://tsx.is/dev-api/node-cli#custom-tsconfig-json-path>

### displayServerEnabled[​](#displayserverenabled "Direct link to displayServerEnabled")

* Type

  `Boolean`

* Default

  `true`

Start a virtual display for the run on Linux when neither `DISPLAY` nor `WAYLAND_DISPLAY` is set. Set to `false` when you run headless or only on a cloud service or remote grid. It only controls whether a display server starts: with only `WAYLAND_DISPLAY` set, the testrunner still sets `XDG_SESSION_TYPE`, `GDK_BACKEND` and `ELECTRON_OZONE_PLATFORM_HINT` to `wayland` for the run. See [Headless & Display Servers](/docs/headless-and-display-servers.md).

### displayServer[​](#displayserver "Direct link to displayServer")

* Type

  `String`

* Default

  `auto`

* Values

  `auto | wayland | xvfb`

Which display server to start. `auto` tries Weston and falls back to Xvfb when Weston is missing or fails to start. `wayland` and `xvfb` only try that server.

### displayServerAutoInstall[​](#displayserverautoinstall "Direct link to displayServerAutoInstall")

* Type

  `Boolean`

* Default

  `false`

Install a missing display server with the system package manager when no installed one starts.

### displayServerAutoInstallMode[​](#displayserverautoinstallmode "Direct link to displayServerAutoInstallMode")

* Type

  `String`

* Default

  `sudo`

* Values

  `root | sudo`

How the built-in install runs: `root` installs only when running as root, `sudo` uses non-interactive `sudo -n` when not root, or installs without it when `sudo` isn't installed.

### displayServerAutoInstallCommand[​](#displayserverautoinstallcommand "Direct link to displayServerAutoInstallCommand")

* Type

  `String | String[]`

A command to run instead of the built-in install, as-is and without `sudo`. It only runs with `displayServerAutoInstall: true`. A string runs in a shell, an array runs without one. With `auto`, it runs for Weston first, and again for Xvfb only if Weston still isn't available or fails to start, and Xvfb is still missing. Set `displayServer` to the server it installs to skip the other server's attempt.

### displayServerWidth[​](#displayserverwidth "Direct link to displayServerWidth")

* Type

  `Number`

* Default

  `1920`

Screen width of the virtual display in pixels.

### displayServerHeight[​](#displayserverheight "Direct link to displayServerHeight")

* Type

  `Number`

* Default

  `1080`

Screen height of the virtual display in pixels.

### displayServerDepth[​](#displayserverdepth "Direct link to displayServerDepth")

* Type

  `Number`

* Default

  `24`

Color depth of the virtual display. Xvfb only.

## Hooks[​](#hooks "Direct link to Hooks")

The WDIO testrunner allows you to set hooks to be triggered at specific times of the test lifecycle. This allows custom actions (e.g. take screenshot if a test fails).

Every hook has as parameter specific information about the lifecycle (e.g. information about the test suite or test). Read more about all hook properties in [our example config](https://github.com/webdriverio/webdriverio/blob/master/examples/wdio.conf.js#L183-L326).

**Note:** Some hooks (`onPrepare`, `onWorkerStart`, `onWorkerEnd` and `onComplete`) are executed in a different process and therefore can not share any global data with the other hooks that live in the worker process.

**Errors that no test reports:** with Jasmine and Cucumber, a promise that rejects when no test or step runs, before the worker ends (for example a command without `await` in the last `afterEach` hook, or in the `after` hook), fails the run, and the worker logs it as `Unhandled promise rejection that no test reports`. The worker goes on, so the reporters still write their reports. If a hook waits for that promise, the worker ends 60 seconds after its last activity, also with its reports. An error that is thrown when no test or step runs (for example in a timer) after the tests started ends the worker at once, with its reports. When the worker ends this way, the hooks that did not run yet (for example `after` or `afterSession`) do not run. Before the tests start (in the `beforeSession` and `before` hooks, or while the session starts), a thrown error ends the worker at once without reports, because no test ran yet, and a promise that rejects follows the rules above. While the Mocha tests run, Mocha handles these errors itself: it ignores an unhandled rejection, and an error thrown after the run ends the worker.

### onPrepare[​](#onprepare "Direct link to onPrepare")

Gets executed once before all workers get launched.

Parameters:

* `config` (`object`): WebdriverIO configuration object
* `param` (`object[]`): list of capabilities details

### onWorkerStart[​](#onworkerstart "Direct link to onWorkerStart")

Gets executed before a worker process is spawned and can be used to initialize specific service for that worker as well as modify runtime environments in an async fashion.

Parameters:

* `cid` (`string`): capability id (e.g 0-0)
* `caps` (`object`): containing capabilities for session that will be spawn in the worker
* `specs` (`string[]`): specs to be run in the worker process
* `args` (`object`): object that will be merged with the main configuration once worker is initialized
* `execArgv` (`string[]`): list of string arguments passed to the worker process

### onWorkerEnd[​](#onworkerend "Direct link to onWorkerEnd")

Gets executed just after a worker process has exited.

Parameters:

* `cid` (`string`): capability id (e.g 0-0)
* `exitCode` (`number`): 0 - success, 1 - fail. A worker that was terminated by a signal reports `128` + the signal number instead, e.g. `139` for a `SIGSEGV`
* `specs` (`string[]`): specs to be run in the worker process
* `retries` (`number`): number of spec level retries used as defined in [*"Add retries on a per-specfile basis"*](/docs/retry.md#add-retries-on-a-per-specfile-basis)
* `signal` (`string`): signal that terminated the worker, e.g. `SIGSEGV`, or `null` if it exited on its own

### beforeSession[​](#beforesession "Direct link to beforeSession")

Gets executed just before initializing the webdriver session and test framework. It allows you to manipulate configurations depending on the capability or spec.

Parameters:

* `config` (`object`): WebdriverIO configuration object
* `caps` (`object`): containing capabilities for session that will be spawn in the worker
* `specs` (`string[]`): specs to be run in the worker process

### before[​](#before "Direct link to before")

Gets executed before test execution begins. At this point you can access to all global variables like `browser`. It is the perfect place to define custom commands.

Parameters:

* `caps` (`object`): containing capabilities for session that will be spawn in the worker
* `specs` (`string[]`): specs to be run in the worker process
* `browser` (`object`): instance of created browser/device session

### beforeSuite[​](#beforesuite "Direct link to beforeSuite")

Hook that gets executed before the suite starts (in Mocha/Jasmine only)

Parameters:

* `suite` (`object`): suite details

### beforeHook[​](#beforehook "Direct link to beforeHook")

Hook that gets executed *before* a hook within the suite starts (e.g. runs before calling beforeEach in Mocha)

Parameters:

* `test` (`object`): test details
* `context` (`object`): test context (represents World object in Cucumber)

### afterHook[​](#afterhook "Direct link to afterHook")

Hook that gets executed *after* a hook within the suite ends (e.g. runs after calling afterEach in Mocha)

Parameters:

* `test` (`object`): test details
* `context` (`object`): test context (represents World object in Cucumber)
* `result` (`object`): hook result (contains `error`, `result`, `duration`, `passed`, `retries` properties)

### beforeTest[​](#beforetest "Direct link to beforeTest")

Function to be executed before a test (in Mocha/Jasmine only).

Parameters:

* `test` (`object`): test details
* `context` (`object`): scope object the test was executed with

### beforeCommand[​](#beforecommand "Direct link to beforeCommand")

Runs before a WebdriverIO command gets executed. For an element command, it runs before WebdriverIO waits for the element (see [Auto-waiting](/docs/autowait.md)).

Parameters:

* `commandName` (`string`): command name
* `args` (`*`): arguments that command would receive

### afterCommand[​](#aftercommand "Direct link to afterCommand")

Runs after a WebdriverIO command gets executed. For an element command, it runs after the wait for the element. When WebdriverIO retries an element command (for example after a stale element), the hook gets the result or the error of the last try.

Parameters:

* `commandName` (`string`): command name
* `args` (`*`): arguments that command would receive
* `result` (`*`): result of the command
* `error` (`Error`): error object if any

### afterTest[​](#aftertest "Direct link to afterTest")

Function to be executed after a test (in Mocha/Jasmine) ends. It also runs after a test times out. With Mocha, the next test starts after this hook ends (Mocha waits for it up to one more timeout of the test, see [Timeouts](/docs/timeouts.md#mocha-timeouts-and-the-webdriverio-hooks)).

Parameters:

* `test` (`object`): test details
* `context` (`object`): scope object the test was executed with
* `result.error` (`Error`): error object in case the test fails, otherwise `undefined`
* `result.result` (`Any`): return object of test function
* `result.duration` (`Number`): duration of test
* `result.passed` (`Boolean`): true if test has passed, otherwise false
* `result.retries` (`Object`): information about single test related retries as defined for [Mocha and Jasmine](/docs/retry.md#rerun-single-tests-in-jasmine-or-mocha) as well as [Cucumber](/docs/retry.md#rerunning-in-cucumber), e.g. `{ attempts: 0, limit: 0 }`, see
* `result` (`object`): hook result (contains `error`, `result`, `duration`, `passed`, `retries` properties)

### afterSuite[​](#aftersuite "Direct link to afterSuite")

Hook that gets executed after the suite has ended (in Mocha/Jasmine only)

Parameters:

* `suite` (`object`): suite details

### after[​](#after "Direct link to after")

Gets executed after all tests are done. You still have access to all global variables from the test.

Parameters:

* `result` (`number`): 0 - test pass, 1 - test fail
* `caps` (`object`): containing capabilities for session that will be spawn in the worker
* `specs` (`string[]`): specs to be run in the worker process

### afterSession[​](#aftersession "Direct link to afterSession")

Gets executed right after terminating the webdriver session.

Parameters:

* `config` (`object`): WebdriverIO configuration object
* `caps` (`object`): containing capabilities for session that will be spawn in the worker
* `specs` (`string[]`): specs to be run in the worker process

### onComplete[​](#oncomplete "Direct link to onComplete")

Gets executed after all workers got shut down and the process is about to exit. An error thrown in the onComplete hook will result in the test run failing.

Parameters:

* `exitCode` (`number`): 0 - success, 1 - fail
* `config` (`object`): WebdriverIO configuration object
* `caps` (`object`): containing capabilities for session that will be spawn in the worker
* `result` (`object`): results object containing test results

### onReload[​](#onreload "Direct link to onReload")

Gets executed when a refresh happens.

Parameters:

* `oldSessionId` (`string`): session ID of the old session
* `newSessionId` (`string`): session ID of the new session

### beforeFeature[​](#beforefeature "Direct link to beforeFeature")

Runs before a Cucumber Feature.

Parameters:

* `uri` (`string`): path to feature file
* `feature` ([`GherkinDocument.IFeature`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/json-to-messages/javascript/src/cucumber-generic/JSONSchema.ts#L8-L17)): Cucumber feature object

### afterFeature[​](#afterfeature "Direct link to afterFeature")

Runs after a Cucumber Feature.

Parameters:

* `uri` (`string`): path to feature file
* `feature` ([`GherkinDocument.IFeature`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/json-to-messages/javascript/src/cucumber-generic/JSONSchema.ts#L8-L17)): Cucumber feature object

### beforeScenario[​](#beforescenario "Direct link to beforeScenario")

Runs before a Cucumber Scenario.

Parameters:

* `world` ([`ITestCaseHookParameter`](https://github.com/cucumber/cucumber-js/blob/ac124f7b2be5fa54d904c7feac077a2657b19440/src/support_code_library_builder/types.ts#L10-L15)): world object containing information on pickle and test step
* `context` (`object`): Cucumber World object

### afterScenario[​](#afterscenario "Direct link to afterScenario")

Runs after a Cucumber Scenario.

Parameters:

* `world` ([`ITestCaseHookParameter`](https://github.com/cucumber/cucumber-js/blob/ac124f7b2be5fa54d904c7feac077a2657b19440/src/support_code_library_builder/types.ts#L10-L15)): world object containing information on pickle and test step
* `result` (`object`): results object containing scenario results
* `result.passed` (`boolean`): true if scenario has passed
* `result.error` (`string`): error stack if scenario failed
* `result.duration` (`number`): duration of scenario in milliseconds
* `context` (`object`): Cucumber World object

### beforeStep[​](#beforestep "Direct link to beforeStep")

Runs before a Cucumber Step.

Parameters:

* `step` ([`Pickle.IPickleStep`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L20-L49)): Cucumber step object
* `scenario` ([`IPickle`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L137-L175)): Cucumber scenario object
* `context` (`object`): Cucumber World object

### afterStep[​](#afterstep "Direct link to afterStep")

Runs after a Cucumber Step.

Parameters:

* `step` ([`Pickle.IPickleStep`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L20-L49)): Cucumber step object
* `scenario` ([`IPickle`](https://github.com/cucumber/common/blob/b94ce625967581de78d0fc32d84c35b46aa5a075/messages/jsonschema/Pickle.json#L137-L175)): Cucumber scenario object
* `result`: (`object`): results object containing step results
* `result.passed` (`boolean`): true if scenario has passed
* `result.error` (`string`): error stack if scenario failed
* `result.duration` (`number`): duration of scenario in milliseconds
* `context` (`object`): Cucumber World object

### beforeAssertion[​](#beforeassertion "Direct link to beforeAssertion")

Hook that gets executed before a WebdriverIO assertion happens.

Parameters:

* `params`: assertion information
* `params.matcherName` (`string`): name of the matcher that the test called (e.g. `toHaveTitle`). For an alias, it is the name of the alias (e.g. `toBeExisting`, not `toExist`).
* `params.expectedValue`: value that is passed into the matcher
* `params.options`: assertion options

### afterAssertion[​](#afterassertion "Direct link to afterAssertion")

Hook that gets executed after a WebdriverIO assertion happened.

Parameters:

* `params`: assertion information
* `params.matcherName` (`string`): name of the matcher that the test called (e.g. `toHaveTitle`). For an alias, it is the name of the alias (e.g. `toBeExisting`, not `toExist`).
* `params.expectedValue`: value that is passed into the matcher
* `params.options`: assertion options
* `params.result` (`object`): result of the matcher, with `pass` (`boolean`) and `message()`. `pass` is `true` when the value matches the expected value, also with `.not`: with `.not`, the assertion passes when `pass` is `false`.
