# WebdriverIO v10 documentation: Running Tests > 18 pages. Index of all sections: https://webdriver.io/llms.txt --- Source: https://webdriver.io/docs/testrunner.md # Testrunner The WebdriverIO testrunner runs your test suite from a configuration file. It starts one worker per capability, wires up your framework, services and reporters, and runs specs in parallel. Use it for every test project; use the [standalone mode](/docs/setuptypes.md) only when you embed WebdriverIO into your own tooling. The testrunner ships in the `@wdio/cli` package: * npm * Yarn * pnpm * Bun ``` npm install --save-dev @wdio/cli ``` ``` yarn add --dev @wdio/cli ``` ``` pnpm add --save-dev @wdio/cli ``` ``` bun add --dev @wdio/cli ``` `npx wdio` runs the same CLI when `@wdio/cli` is not installed yet. npm installs the unscoped [`wdio`](https://www.npmjs.com/package/wdio) package, and that package starts `@wdio/cli`. To set up a new project, run the configuration wizard. It asks a few questions, installs the packages and writes a `wdio.conf.ts`: ``` npx wdio config ``` Then run your tests: ``` npx wdio run wdio.conf.ts ``` `run` is the default command, so `npx wdio wdio.conf.ts` does the same. In your specs, import the session from `@wdio/globals`: test/specs/example.e2e.ts ``` import { browser, $, expect } from '@wdio/globals' describe('webdriver.io', () => { it('has a title', async () => { await browser.url('https://webdriver.io') await expect(browser).toHaveTitle(expect.stringContaining('WebdriverIO')) }) }) ``` See [Configuration File](/docs/configurationfile.md) for every option of `wdio.conf.ts`. ## Commands[​](#commands "Direct link to Commands") ``` $ npx wdio --help wdio [command] Commands: wdio config Initialize WebdriverIO and setup configuration in your current project. wdio install Add a `reporter`, `service`, or `framework` to your WebdriverIO project. wdio repl [option] [capabilities] Run WebDriver session in command line wdio run Run your WDIO configuration file to initialize your tests. (default) wdio session [action..] Drive a browser, mobile app or desktop app from the shell Options: --help Show help [boolean] --version Show version number [boolean] ``` Every command prints its own options with `--help`, e.g. `npx wdio run --help`. ### `wdio config`[​](#wdio-config "Direct link to wdio-config") The `config` command runs the configuration wizard and creates a `wdio.conf.ts` (or `wdio.conf.js`) based on your answers. ``` npx wdio config ``` Pass `--yes` to use the defaults (Mocha, Chrome and page objects) without prompting. Every wizard question also has a flag, so you can answer some or all of them on the command line: ``` npx wdio config --yes --framework cucumber --no-typescript --reporters spec,junit ``` Options: ``` -y, --yes will fill in all config defaults without prompting [boolean] [default: false] -t, --npmTag define NPM tag to use for WebdriverIO related packages [string] [default: "latest"] --help Show help, including a flag for every wizard question [boolean] ``` The wizard installs packages with the package manager that runs it: `pnpm wdio config` uses pnpm, `yarn wdio config` uses Yarn, and `npx` uses npm. `npx wdio config --help` lists the wizard flags and the values they accept. A flag for a question the wizard does not ask for your setup is an error, and so is a value it does not offer. See [Answer the wizard with flags](/docs/gettingstarted.md#answer-the-wizard-with-flags) for examples. ### `wdio run`[​](#wdio-run "Direct link to wdio-run") > This is the default command to run your configuration. The `run` command loads your configuration file and runs your tests. Command line options override the matching options in the configuration file. ``` npx wdio run wdio.conf.ts --spec test/specs/login.e2e.ts ``` Options: ``` --watch Run WebdriverIO in watch mode [boolean] -h, --hostname automation driver host address [string] -p, --port automation driver port [number] --path path to WebDriver endpoints (default "/") [string] -u, --user username if using a cloud service as automation backend [string] -k, --key corresponding access key to the user [string] -l, --logLevel level of logging verbosity [choices: "trace", "debug", "info", "warn", "error", "silent"] --bail stop test runner after specific amount of tests have failed [number] --baseUrl shorten url command calls by setting a base url [string] -w, --waitforTimeout timeout for all waitForXXX commands [number] -s, --updateSnapshots update DOM, image or test snapshots [string] -f, --framework defines the framework (Mocha, Jasmine or Cucumber) to run the specs [string] -r, --reporters reporters to print out the results on stdout [array] --suite overwrites the specs attribute and runs the defined suite [array] --spec run only a certain spec file or wildcard - overrides specs piped from stdin [array] --exclude exclude certain spec file or wildcard from the test run - overrides exclude piped from stdin [array] --repeat Repeat specific specs and/or suites N times [number] --mochaOpts Mocha options --jasmineOpts Jasmine options --cucumberOpts Cucumber options --coverage Enable coverage for browser runner --headless run all browser instances in headless mode, overrides capability settings in wdio.conf.js [boolean] --shard Shard tests and execute only the selected shard. Specify in the one-based form like `--shard x/y`, where x is the current and y the total shard. --cpuProf Enable Node.js CPU profiling for worker processes (--cpu-prof) [boolean] --heapProf Enable Node.js heap profiling for worker processes (--heap-prof) [boolean] --debug Pause failing tests and browser.debug() in an agent session. Only `agent` is supported [string] [choices: "agent"] --tsConfigPath custom path for `tsconfig.json` [string] ``` Examples: ``` # run one suite npx wdio run wdio.conf.ts --suite login # run the first of four shards, e.g. in a CI matrix npx wdio run wdio.conf.ts --shard 1/4 # run all browsers headless, or force headed mode npx wdio run wdio.conf.ts --headless npx wdio run wdio.conf.ts --headless=false # set framework options with dot notation npx wdio run wdio.conf.ts --mochaOpts.timeout 60000 # run a Cucumber scenario by line number npx wdio run wdio.conf.ts --spec ./features/login.feature:5 # use a custom tsconfig.json npx wdio run wdio.conf.ts --tsConfigPath=./configs/bdd-tsconfig.json # pause failing tests and browser.debug() so a coding agent can inspect them npx wdio run wdio.conf.ts --debug=agent ``` `--tsConfigPath` overrides the [`tsConfigPath`](/docs/configurationfile.md) setting of your configuration. See [TypeScript](/docs/typescript.md) for how WebdriverIO compiles your specs with `tsx`. ### `wdio install`[​](#wdio-install "Direct link to wdio-install") The `install` command adds a reporter, service, framework, plugin or runner to an existing project. It installs the package, adds it to your `package.json` and updates your configuration file. ``` npx wdio install service sauce # installs @wdio/sauce-service npx wdio install reporter dot # installs @wdio/dot-reporter npx wdio install framework mocha # installs @wdio/mocha-framework ``` The packages are installed with the package manager that runs the command, so `pnpm wdio install reporter dot` installs with pnpm and `yarn wdio install reporter dot` with Yarn. `npx` and direct calls use npm. If your configuration file is not `wdio.conf.(js|ts|cjs|mjs)` in the current folder, pass its location: ``` npx wdio install service sauce --config="./path/to/wdio.conf.ts" ``` `npx wdio install --help` prints every supported package with its npm name. #### List of supported services[​](#list-of-supported-services "Direct link to List of supported services") ``` visual, ai, vite, nuxt, firefox-profile, gmail, sauce, testingbot, browserstack, lighthouse, vscode, electron, tauri, tauri-plugin, dioxus, appium, camera, eslinter, lambdatest, tvlabs, zafira-listener, reportportal, docker, ui5, wiremock, ng-apimock, slack, cucumber-viewport-logger, intercept, novus-visual-regression, rerun, winappdriver, ywinappdriver, performancetotal, cleanuptotal, aws-device-farm, ms-teams, tesults, azure-devops, google-chat, qmate-service, robonut, qunit, roku, obsidian, null-driver ``` #### List of supported reporters[​](#list-of-supported-reporters "Direct link to List of supported reporters") ``` spec, dot, junit, allure, sumologic, concise, json, reportportal, video, cucumberjs-json, mochawesome, timeline, html, slack, teamcity, delta, testrail, light, jsonhtml ``` #### List of supported frameworks[​](#list-of-supported-frameworks "Direct link to List of supported frameworks") ``` mocha, jasmine, cucumber ``` #### List of supported plugins and runners[​](#list-of-supported-plugins-and-runners "Direct link to List of supported plugins and runners") ``` plugin: wait-for, harness, testing-library runner: local, browser ``` ### `wdio repl`[​](#wdio-repl "Direct link to wdio-repl") The `repl` command starts a WebDriver session and opens an interactive prompt where you run WebdriverIO commands. Use it to try out selectors and commands without writing a spec. See [REPL interface](/docs/repl.md) for more. Start a local Chrome: ``` npx wdio repl chrome ``` Run in the Sauce Labs cloud: ``` npx wdio repl chrome --user $SAUCE_USERNAME --key $SAUCE_ACCESS_KEY ``` Use a capability from your configuration file, by index or by its multi-remote name: ``` npx wdio repl ./wdio.conf.ts 0 -p 9515 ``` Attach to a running [`wdio session`](/docs/session.md) instead of starting a new browser: ``` npx wdio repl --session default ``` `repl` accepts the connection options of the [run command](#wdio-run) (`--hostname`, `--port`, `--path`, `--user`, `--key`, `--logLevel`, ...) and these mobile options. Use the long `--user` and `--udid` forms: `-u` is the short alias of both. ``` -v, --platformVersion Version of OS for mobile devices [string] -d, --deviceName Device name for mobile devices [string] --udid UDID of real mobile devices [string] -s, --session Attach to a running `wdio session` instead of starting a browser [string] ``` ### `wdio session`[​](#wdio-session "Direct link to wdio-session") The `session` command drives a browser, mobile app or desktop app from the shell, one command per call. It is built for coding agents: they open a session, take snapshots, click and type, and export what they did as a test. See [wdio session](/docs/session.md) for the workflow and [wdio session commands](/docs/session-commands.md) for every action. ``` npx wdio session --help ``` ## Next steps[​](#next-steps "Direct link to Next steps") * [Configuration File](/docs/configurationfile.md): every option of `wdio.conf.ts` * [Getting Started](/docs/gettingstarted.md): set up a project with the wizard * [REPL interface](/docs/repl.md): debug commands interactively * [wdio session](/docs/session.md): drive a browser from the shell or an agent --- Source: https://webdriver.io/docs/configurationfile.md # Configuration File The configuration file contains all necessary information to run your test suite. It’s a NodeJS module that exports a JSON. Here is an example configuration with all supported properties and additional information: ``` export const config = { // ================================== // Where should your test be launched // ================================== // runner: 'local', // // ===================== // Server Configurations // ===================== // Host address of the running Selenium server. This information is usually obsolete, as // WebdriverIO automatically connects to localhost. Also if you are using one of the // supported cloud services like Sauce Labs, Browserstack, Testing Bot or TestMu AI (Formerly LambdaTest), you also don't // need to define host and port information (because WebdriverIO can figure that out // from your user and key information). However, if you are using a private Selenium // backend, you should define the `hostname`, `port`, and `path` here. // hostname: 'localhost', port: 4444, path: '/', // Protocol: http | https // protocol: 'http', // // ================= // Service Providers // ================= // WebdriverIO supports Sauce Labs, Browserstack, Testing Bot and TestMu AI (Formerly LambdaTest). (Other cloud providers // should work, too.) These services define specific `user` and `key` (or access key) // values you must put here, in order to connect to these services. // user: 'webdriverio', key: 'xxxxxxxxxxxxxxxx-xxxxxx-xxxxx-xxxxxxxxx', // If you run your tests on Sauce Labs you can specify the region you want to run your tests // in via the `region` property. Available short handles for regions are `us` (default) and `eu`. // These regions are used for the Sauce Labs VM cloud and the Sauce Labs Real Device Cloud. // If you don't provide the region, it defaults to `us`. region: 'us', // // Sauce Labs provides a [headless offering](https://saucelabs.com/products/web-testing/sauce-headless-testing) // that allows you to run Chrome and Firefox tests headless. // headless: false, // // ================== // Specify Test Files // ================== // Define which test specs should run. The pattern is relative to the directory // of the configuration file being run. // // The specs are defined as an array of spec files (optionally using wildcards // that will be expanded). The test for each spec file will be run in a separate // worker process. In order to have a group of spec files run in the same worker // process enclose them in an array within the specs array. // // The path of the spec files will be resolved relative from the directory of // of the config file unless it's absolute. // specs: [ 'test/spec/**', ['group/spec/**'] ], // Patterns to exclude. exclude: [ 'test/spec/multibrowser/**', 'test/spec/mobile/**' ], // // ============ // Capabilities // ============ // Define your capabilities here. WebdriverIO can run multiple capabilities at the same // time. Depending on the number of capabilities, WebdriverIO launches several test // sessions. Within your `capabilities`, you can overwrite which files run with // `wdio:specs` and `wdio:exclude` in order to group specific specs to a specific capability. // // First, you can define how many instances should be started at the same time. Let's // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have // set `maxInstances` to 1. wdio will spawn 3 processes. // // Therefore, if you have 10 spec files and you set `maxInstances` to 10, all spec files // will be tested at the same time and 30 processes will be spawned. // // The property handles how many capabilities from the same test should run tests. // maxInstances: 10, // // Or set a limit to run tests with a specific capability. maxInstancesPerCapability: 10, // // Inserts WebdriverIO's globals (e.g. `browser`, `$` and `$$`) into the global environment. // If you set to `false`, you should import from `@wdio/globals`. Note: WebdriverIO doesn't // handle injection of test framework specific globals. // injectGlobals: true, // // If you have trouble getting all important capabilities together, check out the // Sauce Labs platform configurator - a great tool to configure your capabilities: // https://docs.saucelabs.com/basics/platform-configurator // capabilities: [{ browserName: 'chrome', 'goog:chromeOptions': { // to run chrome headless the following flags are required // (see https://developers.google.com/web/updates/2017/04/headless-chrome) // args: ['--headless', '--disable-gpu'], } // // Parameter to ignore some or all default flags // - if value is true: ignore all DevTools 'default flags' and Puppeteer 'default arguments' // - if value is an array: DevTools filters given default arguments // 'wdio:devtoolsOptions': { // ignoreDefaultArgs: true, // ignoreDefaultArgs: ['--disable-sync', '--disable-extensions'], // } }, { // maxInstances can get overwritten per capability. So if you have an in house Selenium // grid with only 5 firefox instance available you can make sure that not more than // 5 instance gets started at a time. 'wdio:maxInstances': 5, browserName: 'firefox', 'wdio:specs': [ 'test/ffOnly/*' ], 'moz:firefoxOptions': { // flag to activate Firefox headless mode (see https://github.com/mozilla/geckodriver/blob/master/README.md#firefox-capabilities for more details about moz:firefoxOptions) // args: ['-headless'] }, // If outputDir is provided WebdriverIO can capture driver session logs // it is possible to configure which logTypes to exclude. // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs excludeDriverLogs: ['bugreport', 'server'], // // Parameter to ignore some or all Puppeteer default arguments // ignoreDefaultArgs: ['-foreground'], // set value to true to ignore all default arguments }], // // Additional list of node arguments to use when starting child processes execArgv: [], // // =================== // Test Configurations // =================== // Define all options that are relevant for the WebdriverIO instance here // // Level of logging verbosity: trace | debug | info | warn | error | silent logLevel: 'info', // // Set specific log levels per logger // use 'silent' level to disable logger logLevels: { webdriver: 'info', '@wdio/appium-service': 'info' }, // // Set directory to store all logs into outputDir: __dirname, // // If you only want to run your tests until a specific amount of tests have failed use // bail (default is 0 - don't bail, run all tests). bail: 0, // // Set a base URL in order to shorten `url()` command calls. If your `url` parameter starts // with `/`, the `baseUrl` is prepended, not including the path portion of `baseUrl`. // // If your `url` parameter starts without a scheme or `/` (like `some/path`), the `baseUrl` // gets prepended directly. baseUrl: 'http://localhost:8080', // // Default timeout for all waitForXXX commands. waitforTimeout: 1000, // // Add files to watch (e.g. application code or page objects) when running `wdio` command // with `--watch` flag. Globbing is supported. filesToWatch: [ // e.g. rerun tests if I change my application code // './app/**/*.js' ], // // Framework you want to run your specs with. // The following are supported: 'mocha', 'jasmine', and 'cucumber' // See also: https://webdriver.io/docs/frameworks.html // // Make sure you have the wdio adapter package for the specific framework installed before running any tests. framework: 'mocha', // // The number of times to retry the entire specfile when it fails as a whole specFileRetries: 1, // Delay in seconds between the spec file retry attempts specFileRetriesDelay: 0, // Whether or not retried spec files should be retried immediately or deferred to the end of the queue specFileRetriesDeferred: false, // // Test reporter for stdout. // The only one supported by default is 'dot' // See also: https://webdriver.io/docs/dot-reporter.html , and click on "Reporters" in left column reporters: [ 'dot', ['allure', { // // If you are using the "allure" reporter you should define the directory where // WebdriverIO should save all allure reports. outputDir: './' }] ], // // Options to be passed to Mocha. // See the full list at: http://mochajs.org mochaOpts: { ui: 'bdd' }, // // Options to be passed to Jasmine. // See also: https://github.com/webdriverio/webdriverio/tree/main/packages/wdio-jasmine-framework#jasmineopts-options jasmineOpts: { // // Jasmine default timeout defaultTimeoutInterval: 5000, // // The Jasmine framework allows it to intercept each assertion in order to log the state of the application // or website depending on the result. For example, it is pretty handy to take a screenshot every time // an assertion fails. expectationResultHandler: function(passed, assertion) { // do something }, // // Make use of Jasmine-specific grep functionality grep: null, invertGrep: null }, // // If you are using Cucumber you need to specify where your step definitions are located. // See also: https://github.com/webdriverio/webdriverio/tree/main/packages/wdio-cucumber-framework#cucumberopts-options cucumberOpts: { require: [], // (file/dir) require files before executing features backtrace: false, // show full backtrace for errors compiler: [], // ("extension:module") require files with the given EXTENSION after requiring MODULE (repeatable) dryRun: false, // invoke formatters without executing steps failFast: false, // abort the run on first failure snippets: true, // hide step definition snippets for pending steps source: true, // hide source URIs strict: false, // fail if there are any undefined or pending steps tags: '', // (expression) only execute the features or scenarios with tags matching the expression timeout: 20000, // timeout for step definitions ignoreUndefinedDefinitions: false, // Enable this config to treat undefined definitions as warnings. scenarioLevelReporter: false // Enable this to make webdriver.io behave as if scenarios and not steps were the tests. }, // Specify a custom tsconfig path - 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 env var // See the `tsx` docs: https://tsx.is/dev-api/node-cli#custom-tsconfig-json-path // // Note: This setting will be overriden by the TSX_TSCONFIG_PATH env var and/or the cli --tsConfigPath argument if they are specified. // This setting will be ignored if node is unable to parse your wdio.conf.ts file without help from tsx, e.g. if you have path // aliases setup in tsconfig.json and you use those path aliases inside your wdio.config.ts file. // Only use this if you are using a .js config file or your .ts config file is valid JavaScript. tsConfigPath: 'path/to/tsconfig.json', // // ===== // Hooks // ===== // WebdriverIO provides a several hooks you can use to interfere the test process in order to enhance // it and build services around it. You can either apply a single function to it or an array of // methods. If one of them returns with a promise, WebdriverIO will wait until that promise is // resolved to continue. // /** * Gets executed once before all workers get launched. * @param {object} config wdio configuration object * @param {Array.} capabilities list of capabilities details */ onPrepare: function (config, capabilities) { }, /** * 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. * @param {string} cid capability id (e.g 0-0) * @param {object} caps object containing capabilities for session that will be spawn in the worker * @param {object} specs specs to be run in the worker process * @param {object} args object that will be merged with the main configuration once worker is initialized * @param {object} execArgv list of string arguments passed to the worker process */ onWorkerStart: function (cid, caps, specs, args, execArgv) { }, /** * Gets executed after a worker process has exited. * @param {string} cid capability id (e.g 0-0) * @param {number} exitCode 0 - success, 1 - fail * @param {object} specs specs to be run in the worker process * @param {number} retries number of retries used */ onWorkerEnd: function (cid, exitCode, specs, retries) { }, /** * Gets executed before initializing the webdriver session and test framework. It allows you * to manipulate configurations depending on the capability or spec. * @param {object} config wdio configuration object * @param {Array.} capabilities list of capabilities details * @param {Array.} specs List of spec file paths that are to be run */ beforeSession: function (config, capabilities, specs) { }, /** * 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. * @param {Array.} capabilities list of capabilities details * @param {Array.} specs List of spec file paths that are to be run * @param {object} browser instance of created browser/device session */ before: function (capabilities, specs, browser) { }, /** * Gets executed before the suite starts (in Mocha/Jasmine only). * @param {object} suite suite details */ beforeSuite: function (suite) { }, /** * This hook gets executed _before_ every hook within the suite starts. * (For example, this runs before calling `before`, `beforeEach`, `after`, `afterEach` in Mocha.). In Cucumber `context` is the World object. * */ beforeHook: function (test, context, hookName) { }, /** * Hook that gets executed _after_ every hook within the suite ends. * (For example, this runs after calling `before`, `beforeEach`, `after`, `afterEach` in Mocha.). In Cucumber `context` is the World object. */ afterHook: function (test, context, { error, result, duration, passed, retries }, hookName) { }, /** * Function to be executed before a test (in Mocha/Jasmine only) * @param {object} test test object * @param {object} context scope object the test was executed with */ beforeTest: function (test, context) { }, /** * Runs before a WebdriverIO command is executed. * @param {string} commandName hook command name * @param {Array} args arguments that the command would receive */ beforeCommand: function (commandName, args) { }, /** * Runs after a WebdriverIO command gets executed * @param {string} commandName hook command name * @param {Array} args arguments that command would receive * @param {*} result result of the command * @param {Error} error error object, if any */ afterCommand: function (commandName, args, result, error) { }, /** * Function to be executed after a test (in Mocha/Jasmine only) * @param {object} test test object * @param {object} context scope object the test was executed with * @param {Error} result.error error object in case the test fails, otherwise `undefined` * @param {*} result.result return object of test function * @param {number} result.duration duration of test * @param {boolean} result.passed true if test has passed, otherwise false * @param {object} result.retries information about spec related retries, e.g. `{ attempts: 0, limit: 0 }` */ afterTest: function (test, context, { error, result, duration, passed, retries }) { }, /** * Hook that gets executed after the suite has ended (in Mocha/Jasmine only). * @param {object} suite suite details */ afterSuite: function (suite) { }, /** * Gets executed after all tests are done. You still have access to all global variables from * the test. * @param {number} result 0 - test pass, 1 - test fail * @param {Array.} capabilities list of capabilities details * @param {Array.} specs List of spec file paths that ran */ after: function (result, capabilities, specs) { }, /** * Gets executed right after terminating the webdriver session. * @param {object} config wdio configuration object * @param {Array.} capabilities list of capabilities details * @param {Array.} specs List of spec file paths that ran */ afterSession: function (config, capabilities, specs) { }, /** * Gets executed after all workers have shut down and the process is about to exit. * An error thrown in the `onComplete` hook will result in the test run failing. * @param {object} exitCode 0 - success, 1 - fail * @param {object} config wdio configuration object * @param {Array.} capabilities list of capabilities details * @param {} results object containing test results */ onComplete: function (exitCode, config, capabilities, results) { }, /** * Gets executed when a refresh happens. * @param {string} oldSessionId session ID of the old session * @param {string} newSessionId session ID of the new session */ onReload: function(oldSessionId, newSessionId) { }, /** * Cucumber Hooks * * Runs before a Cucumber Feature. * @param {string} uri path to feature file * @param {GherkinDocument.IFeature} feature Cucumber feature object */ beforeFeature: function (uri, feature) { }, /** * * Runs before a Cucumber Scenario. * @param {ITestCaseHookParameter} world world object containing information on pickle and test step * @param {object} context Cucumber World object */ beforeScenario: function (world, context) { }, /** * * Runs before a Cucumber Step. * @param {Pickle.IPickleStep} step step data * @param {IPickle} scenario scenario pickle * @param {object} context Cucumber World object */ beforeStep: function (step, scenario, context) { }, /** * * Runs after a Cucumber Step. * @param {Pickle.IPickleStep} step step data * @param {IPickle} scenario scenario pickle * @param {object} result results object containing scenario results * @param {boolean} result.passed true if scenario has passed * @param {string} result.error error stack if scenario failed * @param {number} result.duration duration of scenario in milliseconds * @param {object} context Cucumber World object */ afterStep: function (step, scenario, result, context) { }, /** * * Runs after a Cucumber Scenario. * @param {ITestCaseHookParameter} world world object containing information on pickle and test step * @param {object} result results object containing scenario results `{passed: boolean, error: string, duration: number}` * @param {boolean} result.passed true if scenario has passed * @param {string} result.error error stack if scenario failed * @param {number} result.duration duration of scenario in milliseconds * @param {object} context Cucumber World object */ afterScenario: function (world, result, context) { }, /** * * Runs after a Cucumber Feature. * @param {string} uri path to feature file * @param {GherkinDocument.IFeature} feature Cucumber feature object */ afterFeature: function (uri, feature) { }, /** * Runs before a WebdriverIO assertion library makes an assertion. * @param {object} params assertion information * @param {string} params.matcherName name of the matcher that the test called (for an alias, the alias name) * @param {*} params.expectedValue value that is passed into the matcher * @param {object} params.options assertion options */ beforeAssertion: function (params) { }, /** * Runs after a WebdriverIO assertion library makes an assertion. * @param {object} params assertion information, the same as in `beforeAssertion` * @param {object} params.result result of the matcher, with `pass` (boolean) and `message()`. * `pass` is true when the value matches, also with `.not` */ afterAssertion: function (params) { } } ``` You can also find a file with all possible options and variations in the [example folder](https://github.com/webdriverio/webdriverio/blob/main/examples/wdio.conf.js). --- Source: https://webdriver.io/docs/capabilities.md # Capabilities A capability is a definition for a remote interface. It helps WebdriverIO to understand in which browser or mobile environment you like to run your tests on. Capabilities are less crucial when developing tests locally as you run it on one remote interface most of the time but becomes more important when running a large set of integration tests in CI/CD. info The format of a capability object is well defined by the [WebDriver specification](https://w3c.github.io/webdriver/#capabilities). The WebdriverIO testrunner will fail early if user defined capabilities do not adhere to that specification. ## Custom Capabilities[​](#custom-capabilities "Direct link to Custom Capabilities") While the amount of fixed defined capabilities is very low, everyone can provide and accept custom capabilities that are specific to the automation driver or remote interface: ### Browser Specific Capability Extensions[​](#browser-specific-capability-extensions "Direct link to Browser Specific Capability Extensions") * `goog:chromeOptions`: [Chromedriver](https://chromedriver.chromium.org/capabilities) extensions, only applicable for testing in Chrome * `moz:firefoxOptions`: [Geckodriver](https://firefox-source-docs.mozilla.org/testing/geckodriver/Capabilities.html) extensions, only applicable for testing in Firefox * `ms:edgeOptions`: [EdgeOptions](https://learn.microsoft.com/en-us/microsoft-edge/webdriver-chromium/capabilities-edge-options) for specifying the environment when using EdgeDriver for testing Chromium Edge ### Cloud Vendor Capability Extensions[​](#cloud-vendor-capability-extensions "Direct link to Cloud Vendor Capability Extensions") * `sauce:options`: [Sauce Labs](https://docs.saucelabs.com/dev/test-configuration-options/#w3c-webdriver-browser-capabilities--optional) * `bstack:options`: [BrowserStack](https://www.browserstack.com/docs/automate/selenium/organize-tests) * `tb:options`: [TestingBot](https://testingbot.com/support/other/test-options) * `LT:Options`: [LambdaTest](https://www.lambdatest.com/support/docs/webdriverio-with-selenium-running-webdriverio-automation-scripts-on-lambdatest-selenium-grid/) * and many more... ### Automation Engine Capability Extensions[​](#automation-engine-capability-extensions "Direct link to Automation Engine Capability Extensions") * `appium:xxx`: [Appium](https://appium.io/docs/en/latest/guides/caps/) * `selenoid:xxx`: [Selenoid](https://github.com/aerokube/selenoid/blob/master/docs/special-capabilities.adoc) * and many more... ### WebdriverIO Capabilities to manage browser driver options[​](#webdriverio-capabilities-to-manage-browser-driver-options "Direct link to WebdriverIO Capabilities to manage browser driver options") WebdriverIO manages installing and running browser driver for you. WebdriverIO uses a custom capability that allows you to pass in parameters to the driver. #### `wdio:chromedriverOptions`[​](#wdiochromedriveroptions "Direct link to wdiochromedriveroptions") Specific options passed into Chromedriver when starting it. #### `wdio:geckodriverOptions`[​](#wdiogeckodriveroptions "Direct link to wdiogeckodriveroptions") Specific options passed into Geckodriver when starting it. For example, `profileRoot` is the folder in which Geckodriver creates the temporary Firefox profile. On Windows in GitHub Actions, WebdriverIO sets it to `RUNNER_TEMP`; see [Firefox on Windows runners](/docs/githubactions.md#firefox-on-windows-runners). #### `wdio:edgedriverOptions`[​](#wdioedgedriveroptions "Direct link to wdioedgedriveroptions") Specific options passed into Edgedriver when starting it. #### `wdio:safaridriverOptions`[​](#wdiosafaridriveroptions "Direct link to wdiosafaridriveroptions") Specific options passed into Safari when starting it. #### `wdio:maxInstances`[​](#wdiomaxinstances "Direct link to wdiomaxinstances") * Type `number` Maximum number of total parallel running workers for the specific browser/capability. Takes precedence over [maxInstances](/docs/configuration.md#maxinstances) and [maxInstancesPerCapability](/docs/configuration.md#maxinstancespercapability). #### `wdio:specs`[​](#wdiospecs "Direct link to wdiospecs") * Type `(String | String[])[]` Define specs for test execution for that browser/capability. Same as the [regular `specs` configuration option](/docs/configuration.md#specs), but specific to the browser/capability. Takes precedence over `specs`. #### `wdio:exclude`[​](#wdioexclude "Direct link to wdioexclude") * Type `String[]` Exclude specs from test execution for that browser/capability. Same as the [regular `exclude` configuration option](/docs/configuration.md#exclude), but specific to the browser/capability. Excludes after the global `exclude` configuration option is applied. #### `wdio:enforceWebDriverClassic`[​](#wdioenforcewebdriverclassic "Direct link to wdioenforcewebdriverclassic") * Type `boolean` By default, WebdriverIO attempts to establish a WebDriver Bidi session. If you don't prefer that, you can set this flag to disable this behavior. For Chrome on Android through Appium (UiAutomator2 driver), WebdriverIO also sets `appium:chromedriverForwardBiDi: true`, so that Appium sends WebDriver Bidi on to Chromedriver. This needs Appium 3.9.0 or later and UiAutomator2 8.7.3 or later. When the WebDriver Bidi server of an Appium browser session can not run browser commands (for example with older versions), WebdriverIO continues the session with WebDriver Classic and logs a warning. #### `wdio:experimentalBiDiCommands`[​](#wdioexperimentalbidicommands "Direct link to wdioexperimentalbidicommands") * Type `boolean` * Default `false` In a WebDriver BiDi session, runs element commands and browser commands like `getTitle`, `getUrl`, `refresh` and `takeScreenshot` over WebDriver BiDi instead of WebDriver Classic. Required for [parallel tests in a spec file](/docs/parallel-tests.md). Experimental: it changes some command behavior in every test, e.g. `addValue` and `clearValue` dispatch synthetic DOM events and `click` is sent through the Actions API. See [Behavior changes of the BiDi element commands](/docs/parallel-tests.md#behavior-changes-of-the-bidi-element-commands). ``` { browserName: 'chrome', 'wdio:experimentalBiDiCommands': true } ``` In every WebDriver BiDi session with Chrome or Edge 137 and later (or when the browser version is not known), with or without this capability, WebdriverIO removes the on-page log of the ChromeDriver BiDi Mapper when the session starts: that log makes each command after a large BiDi message (for example a screenshot) slower ([crbug.com/577213792](https://issues.chromium.org/issues/577213792)). To keep the log, set the environment variable `WDIO_KEEP_BIDI_MAPPER_LOG=1`. #### `wdio:electronVersion`[​](#wdioelectronversion "Direct link to wdioelectronversion") * Type `string` Downloads the Chromedriver bundled with this Electron release instead of the one from Chrome for Testing, for testing an Electron app set as `goog:chromeOptions.binary`. If `browserVersion` is also set, WebdriverIO uses the Chromedriver for that version instead when the Electron release can't be downloaded or `CHROMEDRIVER_CDNURL` is set. Nightly versions come from [electron/nightlies](https://github.com/electron/nightlies/releases). The Electron service sets it for you from the app's Electron version. ``` { browserName: 'chrome', 'wdio:electronVersion': '33.2.1', // a BiDi session replaces the app's window with `data:,` 'wdio:enforceWebDriverClassic': true, 'goog:chromeOptions': { binary: './out/my-app-darwin-arm64/my-app.app/Contents/MacOS/my-app' } } ``` #### Common Driver Options[​](#common-driver-options "Direct link to Common Driver Options") While all drivers offer different parameters for configuration, there are some common ones that WebdriverIO understands and uses for setting up your driver or browser: ##### `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. ##### `binary`[​](#binary "Direct link to binary") * Type `string` Path to a custom driver binary. If set WebdriverIO won't attempt to download a driver but will use the one provided by this path. Make sure the driver is compatible with the browser you are using. You can provide this path via `CHROMEDRIVER_PATH`, `GECKODRIVER_PATH` or `EDGEDRIVER_PATH` environment variables. caution If the driver `binary` is set, WebdriverIO won't attempt to download a driver but will use the one provided by this path. Make sure the driver is compatible with the browser you are using. #### Custom Driver Download Host[​](#custom-driver-download-host "Direct link to Custom Driver Download Host") If the public driver CDNs are not reachable from your environment, e.g. because you run your tests behind a corporate proxy or mirror the drivers in an internal artifact registry, you can point the download to a custom host using the following environment variables: * Chrome: `CHROMEDRIVER_CDNURL`, defaults to `https://storage.googleapis.com/chrome-for-testing-public` * Microsoft Edge: `EDGEDRIVER_CDNURL`, defaults to `https://msedgedriver.microsoft.com` The mirror is expected to serve the driver archives under the same paths as the original CDN, e.g. for Chrome: ``` CHROMEDRIVER_CDNURL=https://artifactory.company.com/chrome-for-testing npx wdio run wdio.conf.js ``` which resolves the driver to `https://artifactory.company.com/chrome-for-testing///chromedriver-.zip`, where `` is one of `linux64`, `linux-arm64`, `mac-x64`, `mac-arm64`, `win32` or `win64`, e.g. `.../140.0.7339.207/mac-arm64/chromedriver-mac-arm64.zip`. Fully offline environments These variables redirect the driver download only. To keep WebdriverIO from reaching the public internet at all, four more conditions have to be met: * **A browser has to be available locally.** If WebdriverIO can't find an installed Chrome or Firefox it downloads the browser too, and that download does not honor these variables. Either install the browser on the machine or point WebdriverIO at it via `goog:chromeOptions.binary` / `moz:firefoxOptions.binary`. * **Use a full version number.** If `browserVersion` is omitted, WebdriverIO reads the exact version from the local browser and no version lookup is needed. If you do set it, use the complete four part version, e.g. `140.0.7339.207`. A release channel (`stable`), a milestone (`140`) or a partial version (`140.0.7339`) requires a version lookup against a public Google endpoint that can't be redirected. * **Chromedriver has to come from Chrome for Testing.** For Chrome older than `153.0.8001.0` on Linux ARM64, and with `wdio:electronVersion` but no `browserVersion`, Chromedriver is downloaded from Electron's GitHub releases, which these variables don't redirect. * **Make sure the mirror actually has the version you need.** If the driver can't be fetched from your host — because the version isn't mirrored, but equally because the url is wrong or the credentials were rejected — WebdriverIO logs a warning and then looks up the closest known good version, which again queries the public endpoint. Check the warning for the host it tried if a run unexpectedly reaches the internet or picks a version you didn't ask for. #### Browser Specific Driver Options[​](#browser-specific-driver-options "Direct link to Browser Specific Driver Options") In order to propagate options to the driver you can use the following custom capabilities: * Chrome or Chromium: `wdio:chromedriverOptions` * Firefox: `wdio:geckodriverOptions` * Microsoft Egde: `wdio:edgedriverOptions` * Safari: `wdio:safaridriverOptions` - wdio:chromedriverOptions - wdio:geckodriverOptions - wdio:edgedriverOptions - wdio:safaridriverOptions ##### adbPort[​](#adbport "Direct link to adbPort") * Type `number` The port on which the ADB driver should run. Example: `9515` ##### urlBase[​](#urlbase "Direct link to urlBase") * Type `string` Base URL path prefix for commands, e.g. `wd/url`. Example: `/` ##### logPath[​](#logpath "Direct link to logPath") * Type `string` Write server log to file instead of stderr, increases log level to `INFO` ##### logLevel[​](#loglevel "Direct link to logLevel") * Type `string` Set log level. Possible options `ALL`, `DEBUG`, `INFO`, `WARNING`, `SEVERE`, `OFF`. ##### verbose[​](#verbose "Direct link to verbose") * Type `boolean` Log verbosely (equivalent to `--log-level=ALL`) ##### silent[​](#silent "Direct link to silent") * Type `boolean` Log nothing (equivalent to `--log-level=OFF`) ##### appendLog[​](#appendlog "Direct link to appendLog") * Type `boolean` Append log file instead of rewriting. ##### replayable[​](#replayable "Direct link to replayable") * Type `boolean` Log verbosely and don't truncate long strings so that the log can be replayed (experimental). ##### readableTimestamp[​](#readabletimestamp "Direct link to readableTimestamp") * Type `boolean` Add readable timestamps to log. ##### enableChromeLogs[​](#enablechromelogs "Direct link to enableChromeLogs") * Type `boolean` Show logs from the browser (overrides other logging options). ##### bidiMapperPath[​](#bidimapperpath "Direct link to bidiMapperPath") * Type `string` Custom bidi mapper path. ##### allowedIps[​](#allowedips "Direct link to allowedIps") * Type `string[]` * Default `['']` Comma-separated allowlist of remote IP addresses which are allowed to connect to EdgeDriver. ##### allowedOrigins[​](#allowedorigins "Direct link to allowedOrigins") * Type `string[]` * Default `['*']` Comma-separated allowlist of request origins which are allowed to connect to EdgeDriver. Using `*` to allow any host origin is dangerous! ##### spawnOpts[​](#spawnopts "Direct link to spawnOpts") * Type `SpawnOptionsWithoutStdio | SpawnOptionsWithStdioTuple` * Default `undefined` Options to be passed into the driver process. See all Geckodriver options in the official [driver package](https://github.com/webdriverio-community/node-geckodriver#options). See all Edgedriver options in the official [driver package](https://github.com/webdriverio-community/node-edgedriver#options). See all Safaridriver options in the official [driver package](https://github.com/webdriverio-community/node-safaridriver#options). ## Special Capabilities for Specific Use Cases[​](#special-capabilities-for-specific-use-cases "Direct link to Special Capabilities for Specific Use Cases") This is a list of examples showing which capabilities need to be applied to achieve a certain use case. ### Run Browser Headless[​](#run-browser-headless "Direct link to Run Browser Headless") Running a headless browser means to run a browser instance without window or UI. This is mostly used within CI/CD environments where no display is used. To run a browser in headless mode, apply the following capabilities: * Chrome * Firefox * Microsoft Edge * Safari ``` { browserName: 'chrome', // or 'chromium' 'goog:chromeOptions': { args: ['headless', 'disable-gpu'] } } ``` ``` browserName: 'firefox', 'moz:firefoxOptions': { args: ['-headless'] } ``` ``` browserName: 'msedge', 'ms:edgeOptions': { args: ['--headless'] } ``` It seems that Safari [doesn't support](https://discussions.apple.com/thread/251837694) running in headless mode. ### Automate Different Browser Channels[​](#automate-different-browser-channels "Direct link to Automate Different Browser Channels") If you like to test a browser version that is not yet released as stable, e.g. Chrome Canary, you can do so by setting capabilities and pointing to the browser you like to start, e.g.: * Chrome * Firefox * Microsoft Edge * Safari When testing on Chrome, WebdriverIO will automatically download the desired browser version and driver for you based on the defined `browserVersion`, e.g.: ``` { browserName: 'chrome', // or 'chromium' browserVersion: '116' // or '116.0.5845.96', 'stable', 'dev', 'canary', 'beta' or 'latest' (same as 'canary') } ``` If you like to test a manually downloaded browser, you can provide a binary path to the browser via: ``` { browserName: 'chrome', // or 'chromium' 'goog:chromeOptions': { binary: '/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary' } } ``` Additionally, if you like to use a manually downloaded driver, you can provide a binary path to the driver via: ``` { browserName: 'chrome', // or 'chromium' 'wdio:chromedriverOptions': { binary: '/path/to/chromdriver' } } ``` When testing on Firefox, WebdriverIO will automatically download the desired browser version and driver for you based on the defined `browserVersion`, e.g.: ``` { browserName: 'firefox', browserVersion: '119.0a1' // or 'latest' } ``` If you like to test a manually downloaded version you can provide a binary path to the browser via: ``` { browserName: 'firefox', 'moz:firefoxOptions': { binary: '/Applications/Firefox\ Nightly.app/Contents/MacOS/firefox' } } ``` Additionally, if you like to use a manually downloaded driver, you can provide a binary path to the driver via: ``` { browserName: 'firefox', 'wdio:geckodriverOptions': { binary: '/path/to/geckodriver' } } ``` When testing on Microsoft Edge, make sure you have the desired browser version installed on your machine. You can point WebdriverIO to the browser to execute via: ``` { browserName: 'msedge', 'ms:edgeOptions': { binary: '/Applications/Microsoft\ Edge\ Canary.app/Contents/MacOS/Microsoft\ Edge\ Canary' } } ``` WebdriverIO will automatically download the desired driver version for you based on the defined `browserVersion`, e.g.: ``` { browserName: 'msedge', browserVersion: '109' // or '109.0.1467.0', 'stable', 'dev', 'canary', 'beta' } ``` Additionally, if you like to use a manually downloaded driver, you can provide a binary path to the driver via: ``` { browserName: 'msedge', 'wdio:edgedriverOptions': { binary: '/path/to/msedgedriver' } } ``` When testing on Safari, make sure you have the [Safari Technology Preview](https://developer.apple.com/safari/technology-preview/) installed on your machine. You can point WebdriverIO to that version via: ``` { browserName: 'safari technology preview' } ``` ## Extend Custom Capabilities[​](#extend-custom-capabilities "Direct link to Extend Custom Capabilities") If you like to define your own set of capabilities in order to e.g. store arbitrary data to be used within the tests for that specific capability, you can do so by e.g. setting: ``` export const config = { // ... capabilities: [{ browserName: 'chrome', 'custom:caps': { // custom configurations } }] } ``` It is advised to follow the [W3C protocol](https://w3c.github.io/webdriver/#dfn-extension-capability) when it comes to capability naming which requires a `:` (colon) character, denoting an implementation specific namespace. Within your tests you can access your custom capability through, e.g.: ``` browser.capabilities['custom:caps'] ``` In order to ensure type safety you can extend WebdriverIOs capability interface via: ``` declare global { namespace WebdriverIO { interface Capabilities { 'custom:caps': { // ... } } } } ``` --- Source: https://webdriver.io/docs/runner.md # Runner A runner in WebdriverIO orchestrates how and where tests are being run when using the testrunner. WebdriverIO currently supports two different types of runner: local and browser runner. ## Local Runner[​](#local-runner "Direct link to Local Runner") The [Local Runner](https://www.npmjs.com/package/@wdio/local-runner) initiates your framework (e.g. Mocha, Jasmine or Cucumber) within worker a process and runs all your test files within your Node.js environment. Every test file is being run in a separate worker process per capability allowing for maximum concurrency. Every worker process uses a single browser instance and therefore runs its own browser session allowing for maximum isolation. Given every test is run in its own isolated process, it is not possible to share data across test files. There are two ways to work around this: * use the [`@wdio/shared-store-service`](https://www.npmjs.com/package/@wdio/shared-store-service) to share data across all workers * group spec files (read more in [Organizing Test Suite](https://webdriver.io/docs/organizingsuites#grouping-test-specs-to-run-sequentially)) If nothing else is defined in the `wdio.conf.js` the Local Runner is the default runner in WebdriverIO. ### Install[​](#install "Direct link to Install") To use the Local Runner you can install it via: ``` npm install --save-dev @wdio/local-runner ``` ### Setup[​](#setup "Direct link to Setup") The Local Runner is the default runner in WebdriverIO so there is no need to define it within your `wdio.conf.js`. If you want to explicitly set it, you can define it as follows: ``` // wdio.conf.js export const { // ... runner: 'local', // ... } ``` ## Browser Runner[​](#browser-runner "Direct link to Browser Runner") As opposed to the [Local Runner](https://www.npmjs.com/package/@wdio/local-runner) the [Browser Runner](https://www.npmjs.com/package/@wdio/browser-runner) initiates and executes the framework within the browser. This allows you to run unit tests or component tests in an actual browser rather than in a JSDOM like many other test frameworks. The test bundle runs in Chrome 90, Edge 90, Firefox 90 and Safari 14.1 or newer. See [Browser support](/docs/component-testing.md#browser-support). While [JSDOM](https://www.npmjs.com/package/jsdom) is widely used for testing purposes, it is in the end not an actual browser nor can you emulate mobile environments with it. With this runner WebdriverIO enables you to easily run your tests in the browser and use WebDriver commands to interact with elements rendered on the page. Here is an overview of running tests within JSDOM vs. WebdriverIOs Browser Runner | | JSDOM | WebdriverIO Browser Runner | | -- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | 1. | Runs your tests within Node.js using a re-implementation of web standards, notably the WHATWG DOM and HTML Standards | Executes your test in an actual browser and runs the code in an environment that your users use | | 2. | Interactions with components can only be imitated via JavaScript | You can use the [WebdriverIO API](/docs/api.md) to interact with elements through the WebDriver protocol | | 3. | Canvas support requires [additional dependencies](https://www.npmjs.com/package/canvas) and [has limitations](https://github.com/Automattic/node-canvas/issues) | You have access to the real [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) | | 4. | JSDOM has some [caveats](https://github.com/jsdom/jsdom#caveats) and unsupported Web APIs | All Web APIs are supported as test run in an actual browser | | 5. | Impossible to detect errors cross browser | Support for all browsers including mobile browser | | 6. | Can **not** test for element pseudo states | Support for pseudo states such as `:hover` or `:active` | This runner uses [Vite](https://vitejs.dev/) to compile your test code and load it in the browser. It comes with presets for the following component frameworks: * React * Preact * Vue.js * Svelte * SolidJS * Stencil Every test file / test file group runs within a single page which means that between each test the page is being reloaded to guarantee isolation between tests. ### Install[​](#install-1 "Direct link to Install") To use the Browser Runner you can install it via: ``` npm install --save-dev @wdio/browser-runner ``` ### Setup[​](#setup-1 "Direct link to Setup") To use the Browser runner, you have to define a `runner` property within your `wdio.conf.js` file, e.g.: ``` // wdio.conf.js export const { // ... runner: 'browser', // ... } ``` ### Runner Options[​](#runner-options "Direct link to Runner Options") The Browser runner allows following configurations: #### `preset`[​](#preset "Direct link to preset") If you test components using one of the mentioned frameworks above, you can define a preset that ensures everything is configured out of the box. This option can't be used together with `viteConfig`. **Type:** `vue` | `svelte` | `solid` | `react` | `preact` | `stencil`
**Example:** wdio.conf.js ``` export const { // ... runner: ['browser', { preset: 'svelte' }], // ... } ``` #### `viteConfig`[​](#viteconfig "Direct link to viteconfig") Define your own [Vite configuration](https://vitejs.dev/config/). You can either pass in a custom object or import an existing `vite.conf.ts` file if you use Vite.js for development. Note that WebdriverIO keeps custom Vite configurations to set up the test harness. **Type:** `string` or [`UserConfig`](https://github.com/vitejs/vite/blob/52e64eb43287d241f3fd547c332e16bd9e301e95/packages/vite/src/node/config.ts#L119-L272) or `(env: ConfigEnv) => UserConfig | Promise`
**Example:** wdio.conf.ts ``` import viteConfig from '../vite.config.ts' export const { // ... runner: ['browser', { viteConfig }], // or just: runner: ['browser', { viteConfig: '../vites.config.ts' }], // or use a function if your vite config contains a lot of plugins // which you only want to resolve when value is read runner: ['browser', { viteConfig: () => ({ // ... }) }], // ... } ``` #### `headless`[​](#headless "Direct link to headless") If set to `true` the runner will update capabilities to run tests headless. By default this is enabled within CI environments where a `CI` environment variable is set to `'1'` or `'true'`. **Type:** `boolean`
**Default:** `false`, set to `true` if `CI` environment variable is set #### `rootDir`[​](#rootdir "Direct link to rootdir") Project root directory. **Type:** `string`
**Default:** `process.cwd()` #### `coverage`[​](#coverage "Direct link to coverage") WebdriverIO supports test coverage reporting through [`istanbul`](https://istanbul.js.org/). See [Coverage Options](#coverage-options) for more details. **Type:** `object`
**Default:** `undefined` ### Coverage Options[​](#coverage-options "Direct link to Coverage Options") The following options allow to configure coverage reporting. #### `enabled`[​](#enabled "Direct link to enabled") Enables coverage collection. **Type:** `boolean`
**Default:** `false` #### `include`[​](#include "Direct link to include") List of files included in coverage as glob patterns. **Type:** `string[]`
**Default:** `[**]` #### `exclude`[​](#exclude "Direct link to exclude") List of files excluded in coverage as glob patterns. **Type:** `string[]`
**Default:** ``` [ 'coverage/**', 'dist/**', 'packages/*/test{,s}/**', '**/*.d.ts', 'cypress/**', 'test{,s}/**', 'test{,-*}.{js,cjs,mjs,ts,tsx,jsx}', '**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}', '**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}', '**/__tests__/**', '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*', '**/.{eslint,mocha,prettier}rc.{js,cjs,yml}', ] ``` #### `extension`[​](#extension "Direct link to extension") List of file extensions the report should include. **Type:** `string | string[]`
**Default:** `['.js', '.cjs', '.mjs', '.ts', '.mts', '.cts', '.tsx', '.jsx', '.vue', '.svelte']` #### `reportsDirectory`[​](#reportsdirectory "Direct link to reportsdirectory") Directory to write coverage report to. **Type:** `string`
**Default:** `./coverage` #### `reporter`[​](#reporter "Direct link to reporter") Coverage reporters to use. See [istanbul documentation](https://istanbul.js.org/docs/advanced/alternative-reporters/) for detailed list of all reporters. **Type:** `string[]`
**Default:** `['text', 'html', 'clover', 'json-summary']` #### `perFile`[​](#perfile "Direct link to perfile") Check thresholds per file. See `lines`, `functions`, `branches` and `statements` for the actual thresholds. **Type:** `boolean`
**Default:** `false` #### `clean`[​](#clean "Direct link to clean") Clean coverage results before running tests. The reports directory is only cleaned when `enabled` is `true`, so existing output in it is left alone while coverage is disabled. **Type:** `boolean`
**Default:** `true` #### `lines`[​](#lines "Direct link to lines") Threshold for lines. **Type:** `number`
**Default:** `undefined` #### `functions`[​](#functions "Direct link to functions") Threshold for functions. **Type:** `number`
**Default:** `undefined` #### `branches`[​](#branches "Direct link to branches") Threshold for branches. **Type:** `number`
**Default:** `undefined` #### `statements`[​](#statements "Direct link to statements") Threshold for statements. **Type:** `number`
**Default:** `undefined` ### Limitations[​](#limitations "Direct link to Limitations") When using the WebdriverIO browser runner, it's important to note that thread blocking dialogs like `alert` or `confirm` cannot be used natively. This is because they block the web page, which means WebdriverIO cannot continue communicating with the page, causing the execution to hang. In such situations, WebdriverIO provides default mocks with default returned values for these APIs. This ensures that if the user accidentally uses synchronous popup web APIs, the execution would not hang. However, it's still recommended for the user to mock these web APIs for better experience. Read more in [Mocking](/docs/component-testing/mocking.md). ### Examples[​](#examples "Direct link to Examples") Make sure to check out the docs around [component testing](https://webdriver.io/docs/component-testing) and have a look into the [example repository](https://github.com/webdriverio/component-testing-examples) for examples using these and various other frameworks. --- Source: https://webdriver.io/docs/frameworks.md # Frameworks WebdriverIO Runner has built-in support for [Mocha](http://mochajs.org/), [Jasmine](http://jasmine.github.io/), [Cucumber.js](https://cucumber.io/), and [Vitest](#using-vitest). You can also integrate it with 3rd-party open-source frameworks, such as [Serenity/JS](#using-serenityjs). Integrating WebdriverIO with test frameworks To integrate WebdriverIO with a test framework, you need an adapter package available on NPM. Note that the adapter package must be installed in the same location where WebdriverIO is installed. So, if you installed WebdriverIO globally, be sure to install the adapter package globally, too. Integrating WebdriverIO with a test framework lets you access the WebDriver instance using the global `browser` variable in your spec files or step definitions. Note that WebdriverIO will also take care of instantiating and ending the Selenium session, so you don't have to do it yourself. ## Using Mocha[​](#using-mocha "Direct link to Using Mocha") First, install the adapter package from NPM: * npm * Yarn * pnpm * Bun ``` npm install @wdio/mocha-framework --save-dev ``` ``` yarn add @wdio/mocha-framework --dev ``` ``` pnpm add @wdio/mocha-framework --save-dev ``` ``` bun add @wdio/mocha-framework --dev ``` By default WebdriverIO provides an [assertion library](/docs/assertion.md) that is built-in which you can start right away: ``` describe('my awesome website', () => { it('should do some assertions', async () => { await browser.url('https://webdriver.io') await expect(browser).toHaveTitle('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO') }) }) ``` WebdriverIO v10 ships [Mocha 12](https://mochajs.org/) and supports Mocha's `BDD` (default), `TDD`, and `QUnit` [interfaces](https://mochajs.org/#interfaces). If you like to write your specs in TDD style, set the `ui` property in your `mochaOpts` config to `tdd`. Now your test files should be written like this: ``` suite('my awesome website', () => { test('should do some assertions', async () => { await browser.url('https://webdriver.io') await expect(browser).toHaveTitle('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO') }) }) ``` If you want to define other Mocha-specific settings, you can do it with the `mochaOpts` key in your configuration file. A list of all options can be found on the [Mocha project website](https://mochajs.org/api/mocha). **Note:** WebdriverIO does not support the deprecated usage of `done` callbacks in Mocha: ``` it('should test something', (done) => { done() // throws "done is not a function" }) ``` ### Mocha Options[​](#mocha-options "Direct link to Mocha Options") The following options can be applied in your `wdio.conf.js` to configure your Mocha environment. **Note:** not all Mocha options are supported. `parallel` still belongs to Mocha's own worker pool and will error here — the WDIO testrunner already parallelizes specs across capabilities and workers. To run the tests of one spec file at the same time, use [`parallelMode`](#parallelmode). Mocha 12's CLI also moved off yargs onto Node's `util.parseArgs`; that only affects a direct `mocha` invocation, not `mochaOpts` passed through `wdio`. You can pass these framework options as arguments, e.g.: ``` wdio run wdio.conf.ts --mochaOpts.grep "my test" --mochaOpts.bail --no-mochaOpts.checkLeaks ``` This will pass along the following Mocha options: ``` { grep: ['my-test'], bail: true checkLeacks: false } ``` The following Mocha options are supported: #### require[​](#require "Direct link to require") * Type `string|string[]` * Default `[]` The `require` option is useful when you want to add or extend some basic functionality (WebdriverIO framework option). #### allowUncaught[​](#allowuncaught "Direct link to allowUncaught") * Type `boolean` * Default `false` Propagate uncaught errors. #### bail[​](#bail "Direct link to bail") * Type `boolean` * Default `false` Bail after first test failure. #### checkLeaks[​](#checkleaks "Direct link to checkLeaks") * Type `boolean` * Default `false` Check for global variable leaks. #### delay[​](#delay "Direct link to delay") * Type `boolean` * Default `false` Delay root suite execution. #### failHookAffectedTests[​](#failhookaffectedtests "Direct link to failHookAffectedTests") * Type `boolean` * Default `true` Report each test skipped by a failing `before` or `beforeEach` hook as a failure. WebdriverIO enables this so a broken setup hook is visible on every spec it skipped. Set it to `false` to report only the hook. #### fgrep[​](#fgrep "Direct link to fgrep") * Type `string` * Default `null` Test filter given string. #### forbidOnly[​](#forbidonly "Direct link to forbidOnly") * Type `boolean` * Default `false` Tests marked `only` fail the suite. #### forbidPending[​](#forbidpending "Direct link to forbidPending") * Type `boolean` * Default `false` Pending tests fail the suite. #### fullTrace[​](#fulltrace "Direct link to fullTrace") * Type `boolean` * Default `false` Full stacktrace upon failure. #### global[​](#global "Direct link to global") * Type `string[]` * Default `[]` Variables expected in global scope. #### grep[​](#grep "Direct link to grep") * Type `RegExp|string` * Default `null` Test filter given regular expression. Mocha 12 accepts modern RegExp flags in this filter (for example `s` or `d`). #### invert[​](#invert "Direct link to invert") * Type `boolean` * Default `false` Invert test filter matches. #### maxParallelContexts[​](#maxparallelcontexts "Direct link to maxParallelContexts") * Type `number` * Default `os.cpus().length` Number of tests that run at the same time when [`parallelMode`](#parallelmode) is set. See [Parallel Tests in a Spec File](/docs/parallel-tests.md#options). #### parallelMode[​](#parallelmode "Direct link to parallelMode") * Type `'contexts' | 'userContexts'` * Default `undefined` Run the tests of a spec file at the same time, each in its own WebDriver BiDi browsing context. `'contexts'` shares cookies and storage between tests, `'userContexts'` isolates them. Requires the `'wdio:experimentalBiDiCommands': true` capability. `bail` and `retries` are not supported in this mode. See [Parallel Tests in a Spec File](/docs/parallel-tests.md). #### retries[​](#retries "Direct link to retries") * Type `number` * Default `0` Number of times to retry failed tests. #### timeout[​](#timeout "Direct link to timeout") * Type `number` * Default `30000` Timeout threshold value (in ms). ## Using Jasmine[​](#using-jasmine "Direct link to Using Jasmine") First, install the adapter package from NPM: * npm * Yarn * pnpm * Bun ``` npm install @wdio/jasmine-framework --save-dev ``` ``` yarn add @wdio/jasmine-framework --dev ``` ``` pnpm add @wdio/jasmine-framework --save-dev ``` ``` bun add @wdio/jasmine-framework --dev ``` You can then configure your Jasmine environment by setting a `jasmineOpts` property in your config. A list of all options can be found on the [Jasmine project website](https://jasmine.github.io/api/edge/Configuration.html). ### Jasmine Options[​](#jasmine-options "Direct link to Jasmine Options") The following options can be applied in your `wdio.conf.js` to configure your Jasmine environment using the `jasmineOpts` property. For more information on these configuration options, check out the [Jasmine docs](https://jasmine.github.io/api/edge/Configuration). You can pass these framework options as arguments, e.g.: ``` wdio run wdio.conf.ts --jasmineOpts.grep "my test" --jasmineOpts.failSpecWithNoExpectations --no-jasmineOpts.random ``` This will pass along the following Jasmine options: ``` { grep: 'my test', failSpecWithNoExpectations: true, random: false } ``` The following Jasmine options are supported: #### defaultTimeoutInterval[​](#defaulttimeoutinterval "Direct link to defaultTimeoutInterval") * Type `number` * Default `60000` Default Timeout Interval for Jasmine operations. #### helpers[​](#helpers "Direct link to helpers") * Type `string[]` * Default `[]` Array of filepaths (and globs) relative to spec\_dir to include before jasmine specs. #### requires[​](#requires "Direct link to requires") * Type `string[]` * Default `[]` The `requires` option is useful when you want to add or extend some basic functionality. #### random[​](#random "Direct link to random") * Type `boolean` * Default `false` Whether to randomize spec execution order. Jasmine's own default is `true`, but WebdriverIO runs the specs in order unless you set this option. #### seed[​](#seed "Direct link to seed") * Type `Function` * Default `null` Seed to use as the basis of randomization. Null causes the seed to be determined randomly at the start of execution. #### failSpecWithNoExpectations[​](#failspecwithnoexpectations "Direct link to failSpecWithNoExpectations") * Type `boolean` * Default `false` Whether to fail the spec if it ran no expectations. By default a spec that ran no expectations is reported as passed. Setting this to true will report such spec as a failure. #### oneFailurePerSpec[​](#onefailureperspec "Direct link to oneFailurePerSpec") * Type `boolean` * Default `false` Stop a spec at its first failed expectation. A failed sync matcher stops the spec at once, and an awaited async matcher stops it when its promise settles. The other specs continue to run. #### specFilter[​](#specfilter "Direct link to specFilter") * Type `Function` * Default `(spec) => true` Function to use to filter specs. #### grep[​](#grep-1 "Direct link to grep") * Type `string|Regexp` * Default `null` Only run tests matching this string or regexp. (Only applicable if no custom `specFilter` function is set) #### invertGrep[​](#invertgrep "Direct link to invertGrep") * Type `boolean` * Default `false` If true it inverts the matching tests and only runs tests that don't match with the expression used in `grep`. (Only applicable if no custom `specFilter` function is set) #### stopOnSpecFailure[​](#stoponspecfailure "Direct link to stopOnSpecFailure") * Type `boolean` * Default `false` Stop the spec file at its first failed spec (`it`): the other specs of the file do not run, also in other `describe` blocks. Other spec files run in their own workers and continue. #### cleanStack[​](#cleanstack "Direct link to cleanStack") * Type `boolean` * Default `true` Remove the lines of `node_modules` packages from the stack traces of failures. #### expectationResultHandler[​](#expectationresulthandler "Direct link to expectationResultHandler") * Type `Function` * Default `null` Called with `(passed, assertion)` for each expectation, for example to take a screenshot when an expectation fails. If the function throws for a passed expectation, the expectation fails with that error. ### Assertions[​](#assertions "Direct link to Assertions") With Jasmine, the global `expect` combines Jasmine's matchers and the [WebdriverIO matchers](/docs/api/expect-webdriverio.md): * Jasmine's matchers (`toBe`, `toEqual`, `toHaveBeenCalled`, …) and the matchers that you add with `jasmine.addMatchers` are synchronous. They return `undefined`, so you do not need `await`. * WebdriverIO matchers, Jasmine's async matchers (`toBeResolved`, `toBeRejectedWith`, …) and the matchers that you add with `jasmine.addAsyncMatchers` return a promise. Always `await` them. Use `expect()` for both kinds: it sends each matcher to Jasmine's `expect` or `expectAsync` for you. `await expectAsync($('#logo')).toBeDisplayed()` also works. For TypeScript, `@wdio/jasmine-framework` in `types` also gives `expectAsync()` the WebdriverIO matchers. ``` it('checks the page', async () => { expect([1, 2]).toHaveSize(2) // Jasmine, sync await expect($('#logo')).toHaveSize({ width: 32, height: 32 }) // WebdriverIO, async await expect(loadData()).toBeResolved() // Jasmine async matcher }) ``` `toHaveSize` exists in both libraries. The WebdriverIO matcher runs on WebdriverIO values: an element, an element array or `Element[]` (for example the result of `$$().filter()`), a multi-remote element, a browser, a browsing context, a mock, the `some()` wrapper, or a promise such as a chainable `$()`. Jasmine's matcher runs on every other value. The asymmetric matchers of both libraries work, in Jasmine and in WebdriverIO matchers: `jasmine.any()`, `jasmine.objectContaining()`, `jasmine.stringMatching()`, … and `expect.any()`, `expect.stringContaining()`, `expect.oneOf()`, `expect.multiRemote()`, `expect.not.stringContaining()`, …. To use `some()`, import it: ``` import { some } from 'expect-webdriverio/api' await expect(some($$('li'))).toHaveAttribute('data-state', 'on') ``` The Jest parts of `expect` are not available with Jasmine: Jest-only matchers such as `toStrictEqual` or `toHaveLength`, and `expect.soft()`. To add a custom matcher, use `expect.extend()` in a spec file or the `before` hook (see [Custom Matchers](/docs/custommatchers.md)), or `jasmine.addMatchers` for a sync matcher and `jasmine.addAsyncMatchers` for an async matcher. For TypeScript, add `jasmine` to `types`, see [TypeScript Setup](/docs/typescript.md). ## Using Cucumber[​](#using-cucumber "Direct link to Using Cucumber") First, install the adapter package from NPM: * npm * Yarn * pnpm * Bun ``` npm install @wdio/cucumber-framework --save-dev ``` ``` yarn add @wdio/cucumber-framework --dev ``` ``` pnpm add @wdio/cucumber-framework --save-dev ``` ``` bun add @wdio/cucumber-framework --dev ``` If you want to use Cucumber, set the `framework` property to `cucumber` by adding `framework: 'cucumber'` to the [config file](/docs/configurationfile.md) . Options for Cucumber can be given in the config file with `cucumberOpts`. Check out the whole list of options [here](https://github.com/webdriverio/webdriverio/tree/main/packages/wdio-cucumber-framework#cucumberopts-options). The adapter uses Cucumber 13. `tagExpression` has been removed; filter with `tags`. See the [v10 migration guide](/docs/v10-migration.md#cucumber). To get up and running quickly with Cucumber, have a look on our [`cucumber-boilerplate`](https://github.com/webdriverio/cucumber-boilerplate) project that comes with all the step definitions you need to get stared, and you'll be writing feature files right away. ### Cucumber Options[​](#cucumber-options "Direct link to Cucumber Options") The following options can be applied in your `wdio.conf.js` to configure your Cucumber environment using the `cucumberOpts` property: Adjusting options through the command line The `cucumberOpts`, such as custom `tags` for filtering tests, can be specified through the command line. This is accomplished by using the `cucumberOpts.{optionName}="value"` format. For example, if you want to run only the tests that are tagged with `@smoke`, you can use the following command: ``` # When you only want to run tests that hold the tag "@smoke" npx wdio run ./wdio.conf.js --cucumberOpts.tags="@smoke" npx wdio run ./wdio.conf.js --cucumberOpts.name="some scenario name" --cucumberOpts.failFast ``` This command sets the `tags` option in `cucumberOpts` to `@smoke`, ensuring that only tests with this tag are executed. #### backtrace[​](#backtrace "Direct link to backtrace") * Type `Boolean` * Default `false` Show full backtrace for errors. #### requireModule[​](#requiremodule "Direct link to requireModule") * Type `string[]` * Default `[]` Require modules prior to requiring any support files. Example: ``` cucumberOpts: { requireModule: ['@babel/register'] // or requireModule: [ [ '@babel/register', { rootMode: 'upward', ignore: ['node_modules'] } ] ] } ``` #### failFast[​](#failfast "Direct link to failFast") * Type `boolean` * Default `false` Abort the run on first failure. #### name[​](#name "Direct link to name") * Type `RegExp[]` * Default `[]` Only execute the scenarios with name matching the expression (repeatable). #### require[​](#require-1 "Direct link to require") * Type `string[]` * Default `[]` Require files containing your step definitions before executing features. You can also specify a glob to your step definitions. Example: ``` cucumberOpts: { require: [path.join(__dirname, 'step-definitions', 'my-steps.js')] } ``` #### import[​](#import "Direct link to import") * Type `String[]` * Default `[]` Paths to where your support code is, for ESM. Example: ``` cucumberOpts: { import: [path.join(__dirname, 'step-definitions', 'my-steps.js')] } ``` #### strict[​](#strict "Direct link to strict") * Type `boolean` * Default `true` Fail the run on a pending step. The default is `true`, as in Cucumber. The reporters still show the step as pending (Cucumber shows it as a warning), and the worker logs a warning that names the scenarios with a pending step or hook. An undefined step fails the run also without `strict`, unless [`ignoreUndefinedDefinitions`](#ignoreundefineddefinitions) is `true`. #### tags[​](#tags "Direct link to tags") * Type `String` * Default `""` Only execute the features or scenarios with tags matching the expression. A feature file with no matching scenario is reported as skipped and starts no browser session. Please see the [Cucumber documentation](https://docs.cucumber.io/cucumber/api/#tag-expressions) for more details. #### timeout[​](#timeout-1 "Direct link to timeout") * Type `Number` * Default `60000` Timeout in milliseconds for step definitions. #### retry[​](#retry "Direct link to retry") * Type `Number` * Default `0` Specify the number of times to retry failing test cases. #### retryTagFilter[​](#retrytagfilter "Direct link to retryTagFilter") * Type `String` Only retry the scenarios with tags matching the tag expression. Requires [`retry`](#retry). #### language[​](#language "Direct link to language") * Type `String` * Default `en` Default language for your feature files #### order[​](#order "Direct link to order") * Type `String` * Default `defined` Run the scenarios in the order of the feature files (`'defined'`) or in a random order (`'random'`). With `'random:'`, for example `'random:42'`, a random order is the same in each run. With `'random'`, the log shows the seed of the run (`Random order using seed: 42`). #### format[​](#format "Direct link to format") * Type `string[]` Name and output file path of formatter to use. WebdriverIO primarily supports only the [Formatters](https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md) that writes output to a file. Formatters don't run with [`parallelMode`](#parallelmode-1). #### formatOptions[​](#formatoptions "Direct link to formatOptions") * Type `object` Options to be provided to formatters #### tagsInTitle[​](#tagsintitle "Direct link to tagsInTitle") * Type `Boolean` * Default `false` Add cucumber tags to feature or scenario name ***Please note that this is a @wdio/cucumber-framework specific option and not recognized by cucumber-js itself***
#### ignoreUndefinedDefinitions[​](#ignoreundefineddefinitions "Direct link to ignoreUndefinedDefinitions") * Type `Boolean` * Default `false` Report an undefined step as pending, with `(undefined step)` at the end of its title, and do not fail the run for it. ***Please note that this is a @wdio/cucumber-framework specific option and not recognized by cucumber-js itself***
#### failAmbiguousDefinitions[​](#failambiguousdefinitions "Direct link to failAmbiguousDefinitions") * Type `Boolean` * Default `false` Report an ambiguous step (a step that matches more than one step definition) as failed, with the list of the matching step definitions. With `false`, the step is reported as skipped, with the list as its reason. In both cases, the run fails. Exception: without `parallelMode`, the run passes with `ignoreUndefinedDefinitions: true` and `failAmbiguousDefinitions: false`. ***Please note that this is a @wdio/cucumber-framework specific option and not recognized by cucumber-js itself***
#### profiles[​](#profiles "Direct link to profiles") * Type `string[]` * Default `[]` The profiles of the Cucumber configuration file to use. Cucumber merges the values in this order: Cucumber's defaults, then the profiles or the configuration file (without [`file`](#file), Cucumber's default file in the working folder, for example `cucumber.js`), then `cucumberOpts`. So a value in `cucumberOpts` wins over the profile, and a profile value wins over Cucumber's default. `tags` and `retryTagFilter` of both are joined with `and`, and lists (for example `require`, `import`, `name`) are added together. A folder in the `require` or `import` of a profile is not loaded (use a glob). The `paths`, `requireModule` and `loader` of a profile or configuration file are not used: the feature files come from `specs`, the modules from `cucumberOpts.requireModule`, and the worker logs a warning. `parallel` and `shard` of a profile are not used either (WebdriverIO runs the workers), and a profile does not turn on `publish`: set it in `cucumberOpts`. #### file[​](#file "Direct link to file") * Type `string | false` * Default `undefined` Path of the Cucumber configuration file to load (absolute, or from the working folder), or `false` to load none. Without it, Cucumber looks for its default configuration files. #### dryRun[​](#dryrun "Direct link to dryRun") * Type `Boolean` * Default `false` Run no step and no hook: Cucumber only matches each step with its step definitions, so undefined and ambiguous steps are still reported. The run does not fail. #### worldParameters[​](#worldparameters "Direct link to worldParameters") * Type `object` * Default `{}` Parameters for your World, as `this.parameters`. #### scenarioLevelReporter[​](#scenariolevelreporter "Direct link to scenarioLevelReporter") * Type `Boolean` * Default `false` Report each scenario as one test. Its steps and hooks are not reported. A `BeforeAll` / `AfterAll` is still reported, as a hook of the feature. ***Please note that this is a @wdio/cucumber-framework specific option and not recognized by cucumber-js itself***
#### parallelMode[​](#parallelmode-1 "Direct link to parallelMode") * Type `'contexts' | 'userContexts'` * Default `undefined` Run the scenarios of a feature file at the same time, each in its own WebDriver BiDi browsing context. `'contexts'` shares cookies and storage between scenarios, `'userContexts'` isolates them. Requires the `'wdio:experimentalBiDiCommands': true` capability. See [Parallel Tests in a Spec File](/docs/parallel-tests.md). ***Please note that this is a @wdio/cucumber-framework specific option and not recognized by cucumber-js itself***
#### maxParallelContexts[​](#maxparallelcontexts-1 "Direct link to maxParallelContexts") * Type `number` * Default `os.cpus().length` Number of scenarios that run at the same time when [`parallelMode`](#parallelmode-1) is set. See [Parallel Tests in a Spec File](/docs/parallel-tests.md#options). ***Please note that this is a @wdio/cucumber-framework specific option and not recognized by cucumber-js itself***
### Skipping tests in cucumber[​](#skipping-tests-in-cucumber "Direct link to Skipping tests in cucumber") Note that if you want to skip a test using regular cucumber test filtering capabilities available in `cucumberOpts`, you will do it for all the browsers and devices configured in the capabilities. In order to be able to skip scenarios only for specific capabilities combinations without having a session started if not necessary, webdriverio provides the following specific tag syntax for cucumber: `@skip([condition])` were condition is an optional combination of capabilities properties with their values that when **all** matched with cause the tagged scenario or feature to be skipped. Of course you can add several tags to scenarios and features to skip a tests under several different conditions. You can also use the '@skip' annotation to skip tests without changing `tags`. In this case the skipped tests will be displayed in the test report. Here you have some examples of this syntax: * `@skip` or `@skip()`: will always skip the tagged item * `@skip(browserName="chrome")`: the test will not be executed against chrome browsers. * `@skip(browserName="firefox";platformName="linux")`: will skip the test in firefox over linux executions. * `@skip(browserName=["chrome","firefox"])`: tagged items will be skipped for both chrome and firefox browsers. * `@skip(browserName=/i.*explorer/)`: capabilities with browsers matching the regexp will be skipped (like `iexplorer`, `internet explorer`, `internet-explorer`, ...). ### Import Step Definition Helper[​](#import-step-definition-helper "Direct link to Import Step Definition Helper") In order to use step definition helper like `Given`, `When` or `Then` or hooks, you are suppose to import then from `@cucumber/cucumber`, e.g. like this: ``` import { Given, When, Then } from '@cucumber/cucumber' ``` Now, if you use Cucumber already for other types of tests unrelated to WebdriverIO for which you use a specific version you need to import these helpers in your e2e tests from the WebdriverIO Cucumber package, e.g.: ``` import { Given, When, Then, world, context } from '@wdio/cucumber-framework' ``` This ensures that you use the right helpers within the WebdriverIO framework and allows you to use an independent Cucumber version for other types of testing. ### Publishing Report[​](#publishing-report "Direct link to Publishing Report") Cucumber provides a feature to publish your test run reports to `https://reports.cucumber.io/`, which can be controlled either by setting the `publish` flag in `cucumberOpts` or by configuring the `CUCUMBER_PUBLISH_TOKEN` environment variable. However, when you use `WebdriverIO` for test execution, there's a limitation with this approach. It updates the reports separately for each feature file, making it difficult to view a consolidated report. To overcome this limitation, we've introduced a promise-based method called `publishCucumberReport` within `@wdio/cucumber-framework`. This method should be called in the `onComplete` hook, which is the optimal place to invoke it. `publishCucumberReport` requires the input of the report directory where cucumber message reports are stored. You can generate `cucumber message` reports by configuring the `format` option in your `cucumberOpts`. It's highly recommended to provide a dynamic file name within the `cucumber message` format option to prevent overwriting reports and ensure that each test run is accurately recorded. Before using this function, make sure to set the following environment variables: * CUCUMBER\_PUBLISH\_REPORT\_URL: The URL where you want to publish the Cucumber report. If not provided, the default URL '' will be used. * CUCUMBER\_PUBLISH\_REPORT\_TOKEN: The authorization token required to publish the report. If this token is not set, the function will exit without publishing the report. Here's an example of the necessary configurations and code samples for implementation: ``` import { v4 as uuidv4 } from 'uuid' import { publishCucumberReport } from '@wdio/cucumber-framework'; export const config = { // ... Other Configuration Options cucumberOpts: { // ... Cucumber Options Configuration format: [ ['message', `./reports/${uuidv4()}.ndjson`], ['json', './reports/test-report.json'] ] }, async onComplete() { await publishCucumberReport('./reports'); } } ``` Please note that `./reports/` is the directory where `cucumber message` reports will be stored. ## Using Vitest[​](#using-vitest "Direct link to Using Vitest") `@wdio/vitest-framework` runs specs written in [Vitest](https://vitest.dev/) syntax (`describe`, `test`, `test.concurrent`, `test.extend`) through the WDIO testrunner. Vitest schedules the tests, so the testrunner starts no WDIO workers. `wdio.conf.ts` stays the source of truth for specs, capabilities, connection options and hooks. Use it when you want Vitest's API, especially [fixtures](/docs/pageobjects.md#page-objects-as-fixtures) and `test.concurrent`. Otherwise Mocha is the default choice. First, install the adapter package and `vitest` from NPM. `vitest` is a peer dependency, so your project and the adapter share one copy. `expect-webdriverio` is installed with the adapter: * npm * Yarn * pnpm * Bun ``` npm install @wdio/vitest-framework vitest --save-dev ``` ``` yarn add @wdio/vitest-framework vitest --dev ``` ``` pnpm add @wdio/vitest-framework vitest --save-dev ``` ``` bun add @wdio/vitest-framework vitest --dev ``` Then set `framework: 'vitest'` in your [config file](/docs/configurationfile.md): wdio.conf.ts ``` export const config: WebdriverIO.Config = { framework: 'vitest', specs: ['./test/specs/**/*.spec.ts'], baseUrl: 'https://the-internet.herokuapp.com', capabilities: [{ browserName: 'chrome', webSocketUrl: true, 'wdio:experimentalBiDiCommands': true }], vitestOpts: { parallelMode: 'userContexts' } } ``` Run it like any other WDIO project: ``` npx wdio run wdio.conf.ts ``` Vitest globals are enabled at runtime, and `browser`, `driver`, `$`, `$$` and `expect` are globals as well. Import `describe`, `test` and the hooks from `vitest`, so TypeScript knows their types: test/specs/login.spec.ts ``` import { describe, test } from 'vitest' describe('login page', () => { test('shows the form', async () => { await browser.url('/login') await expect($('#login')).toBeDisplayed() }) }) ``` The global `expect` is the WebdriverIO [assertion library](/docs/assertion.md) (`expect-webdriverio`), which replaces Vitest's own `expect`. `waitforTimeout` and `waitforInterval` from the config set its defaults. Never `import { expect } from 'vitest'`. That `expect` has no WebdriverIO matchers such as `toBeDisplayed`. For TypeScript, add `@wdio/vitest-framework` to `types` so `vitestOpts` is typed. It also provides the Vitest globals (`describe`, `test` and the hooks) without imports, see [TypeScript Setup](/docs/typescript.md): tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types", "@wdio/vitest-framework"] } } ``` ### How Vitest runs your specs[​](#how-vitest-runs-your-specs "Direct link to How Vitest runs your specs") * Every capability becomes one Vitest project, named `-`, for example `chrome-0`. * Every spec file gets its own browser session. The session starts in `beforeAll` and is deleted in `afterAll`. * The WDIO hooks `beforeSession`, `before`, `after` and `afterSession` run once per spec file, and `beforeTest` and `afterTest` once per test. Worker services (for example Sauce Labs, BrowserStack or Appium) are initialized like in the WDIO runner, so their hooks run too. * The console output comes from Vitest. File reporters from `wdio.conf.ts`, such as `junit`, `allure` or `json`, receive the Vitest results. Every spec file and capability is reported as one job. Skipped and `todo` tests are reported as pending. * `maxInstances` (or `wdio:maxInstances` per capability) sets Vitest's `maxWorkers`, and `bail` sets Vitest's `bail`. * `runnerEnv` is passed to the Vitest workers as Vitest's `env`, with `NODE_ENV` defaulting to `test`. `vitestOpts.env` is merged on top and wins. `NODE_OPTIONS` in `runnerEnv` only reaches the worker's `process.env`, because Vitest has already forked the worker. Node flags such as `--import` do not apply to it. ### Concurrent tests[​](#concurrent-tests "Direct link to Concurrent tests") `test.concurrent` runs the tests of one spec file at the same time, each in its own browser window (browsing context). Every command in the test, including the ones in your page objects and fixtures, targets that window. The window is closed when the test ends, also when it fails. This needs [`parallelMode`](#parallelmode-2), a WebDriver BiDi session (`webSocketUrl: true`) and the `'wdio:experimentalBiDiCommands': true` capability. Without that capability, commands use classic WebDriver and cannot target the test's window. It changes how element commands are implemented in every test of the session, see [Behavior changes of the BiDi element commands](/docs/parallel-tests.md#behavior-changes-of-the-bidi-element-commands). test/specs/checkout.spec.ts ``` import { describe, test } from 'vitest' describe('checkout', () => { test.concurrent('guest', async () => { await browser.url('/checkout') await expect($('h1')).toHaveText('Checkout') }) test.concurrent('member', async () => { await browser.url('/checkout?member=1') await expect($('h1')).toHaveText('Checkout') }) }) ``` Without `parallelMode`, `test.concurrent` fails with: ``` test.concurrent needs vitestOpts.parallelMode ('contexts' | 'userContexts'): concurrent tests would share one window ``` Without the capability, it fails with: ``` test.concurrent with vitestOpts.parallelMode needs the 'wdio:experimentalBiDiCommands': true capability, so commands run in the window of their test ``` ### Vitest Options[​](#vitest-options "Direct link to Vitest Options") Set them in `vitestOpts` in your `wdio.conf.ts`. #### parallelMode[​](#parallelmode-2 "Direct link to parallelMode") Runs `test.concurrent` tests at the same time, each in its own browsing context. Requires a WebDriver BiDi session and the `'wdio:experimentalBiDiCommands': true` capability. * `'contexts'`: windows share the default user context, so cookies, `localStorage` and service workers are shared across concurrent tests. * `'userContexts'`: each test gets its own user context, so storage is isolated per test. Pick this when tests log in or change cookies. `browser.mock()` remains session-wide in both modes. Type: `'contexts' | 'userContexts'`
Default: `undefined` #### maxParallelContexts[​](#maxparallelcontexts-2 "Direct link to maxParallelContexts") Maximum number of `test.concurrent` tests that run at once. Maps to Vitest's `maxConcurrency` and only applies when `parallelMode` is set. Type: `number`
Default: `os.cpus().length` #### Other Vitest options[​](#other-vitest-options "Direct link to Other Vitest options") All other keys are passed to Vitest's [`test` config](https://vitest.dev/config/) and override this framework's defaults, for example `testTimeout` (default `60000`), `hookTimeout` (default: `connectionRetryTimeout`, else `120000`, because `beforeAll` starts the session), `retry` or `reporters`. With `retry`, every attempt is reported to the WDIO reporters: the failed ones as retries, the last one as the test result. The framework controls some keys itself: * `include` is always the specs resolved from `wdio.conf.ts` (respecting `--spec` and `exclude`), so `vitestOpts.include` is ignored. * `pool` is always `'forks'`. * `setupFiles` from `vitestOpts` runs after the framework's own setup file instead of replacing it. * A `vitest.config.ts` file is not read. Put Vitest options in `vitestOpts`. ### Limitations[​](#limitations "Direct link to Limitations") * Multi-remote capabilities are not supported yet. * `expect.poll` is not available, because the global `expect` comes from `expect-webdriverio`. * `switchWindow` and `switchFrame` throw in a WebDriver BiDi session, which `parallelMode` requires. Inside concurrent tests, `getWindowSize`, `setWindowSize`, `throttleCPU`, `throttleNetwork` and classic window and frame protocol commands such as `switchToWindow` also throw, because they change session-wide state. * The hooks `beforeSuite`, `afterSuite`, `beforeHook`, `afterHook`, `beforeAssertion`, `afterAssertion`, `onWorkerStart` and `onWorkerEnd` are not run, in `wdio.conf.ts` or in services. * `hook:start` / `hook:end` events are sent per hook kind and attempt, not per hook: one pair for all `beforeEach` hooks and one for all `afterEach` hooks, with no duration. A failed hook ends with `state: 'fail'` and its error. A failing `beforeAll` / `afterAll` is reported separately, see below. Reporter runtime API calls made inside a `beforeEach` / `afterEach` hook are attributed to the test, not to the hook. * `--watch`, `--repeat` and per-capability `wdio:specs` / `wdio:exclude` are not supported yet. The testrunner stops with an error instead of ignoring them. * WebDriver commands are not sent to the WDIO reporters, because the reporters run in the launcher and the commands run in the Vitest workers. Allure therefore shows no WebDriver steps and no automatic screenshots (`disableWebdriverStepsReporting` and `disableWebdriverScreenshotsReporting` have no effect), the video reporter records nothing, and the HTML reporter shows no automatic screenshots. Attach screenshots explicitly, for example `allure.addAttachment('screenshot', Buffer.from(await browser.takeScreenshot(), 'base64'), 'image/png')` in `afterTest` or `afterEach`. The `beforeCommand` / `afterCommand` hooks of `wdio.conf.ts` and of worker services still run. Calls of the HTML reporter (`ReportEvents.logMessage`, `logScreenshot` and `videoCapture`) are relayed, so their logs, screenshots and videos reach the report; WebDriver commands still do not. * Top-level config changes made in `onPrepare` do not reach the specs, because each Vitest worker parses the config file again. Changes to capabilities do reach them. * Reporter runtime APIs such as `addStep` and `addAttachment` from `@wdio/allure-reporter` or `addProperty` from `@wdio/junit-reporter` work from tests and `beforeEach` / `afterEach` hooks. Calls in `beforeAll` / `afterAll` are dropped. With exactly one Allure reporter in the final reporter list (after `onPrepare` ran), the launcher tells the Vitest workers its results folder, they write Allure attachments there and only the path travels to the launcher. Otherwise attachments are sent through the launcher. * A failing `beforeAll` or `afterAll` is reported to WDIO reporters as a failed hook, so the JUnit reporter adds a failing testcase for it. Other `beforeAll` / `afterAll` results are not reported. * Soft assertions (`expect.soft` from `expect-webdriverio`) fail the test at its end unless `autoAssertOnTestEnd` is `false`. `expect-webdriverio` tracks one current test per worker, so in `test.concurrent` tests the failures can be attributed to the wrong test. Use Vitest's own `expect.soft` from the test context there. * Soft assertions outside a test (in `beforeAll` or `afterAll`) are not asserted: their failures are dropped. ## Using Serenity/JS[​](#using-serenityjs "Direct link to Using Serenity/JS") [Serenity/JS](https://serenity-js.org?pk_campaign=wdio8\&pk_source=webdriver.io) is an open-source framework designed to make acceptance and regression testing of complex software systems faster, more collaborative, and easier to scale. For WebdriverIO test suites, Serenity/JS offers: * [Enhanced Reporting](https://serenity-js.org/handbook/reporting/?pk_campaign=wdio8\&pk_source=webdriver.io) - You can use Serenity/JS as a drop-in replacement of any built-in WebdriverIO framework to produce in-depth test execution reports and living documentation of your project. * [Screenplay Pattern APIs](https://serenity-js.org/handbook/design/screenplay-pattern/?pk_campaign=wdio8\&pk_source=webdriver.io) - To make your test code portable and reusable across projects and teams, Serenity/JS gives you an optional [abstraction layer](https://serenity-js.org/api/webdriverio?pk_campaign=wdio8\&pk_source=webdriver.io) on top of native WebdriverIO APIs. * [Integration Libraries](https://serenity-js.org/api/core/?pk_campaign=wdio8\&pk_source=webdriver.io) - For test suites that follow the Screenplay Pattern, Serenity/JS also provides optional integration libraries to help you write [API tests](https://serenity-js.org/api/rest/?pk_campaign=wdio8\&pk_source=webdriver.io), [manage local servers](https://serenity-js.org/api/local-server/?pk_campaign=wdio8\&pk_source=webdriver.io), [perform assertions](https://serenity-js.org/api/assertions/?pk_campaign=wdio8\&pk_source=webdriver.io), and more! ![Serenity BDD Report Example](/assets/images/serenity-bdd-reporter-c90e03e1dcfdd70c21fa0acca0cd40b5.png) ### Installing Serenity/JS[​](#installing-serenityjs "Direct link to Installing Serenity/JS") To add Serenity/JS to an [existing WebdriverIO project](https://webdriver.io/docs/gettingstarted), install the following Serenity/JS modules from NPM: * npm * Yarn * pnpm * Bun ``` npm install @serenity-js/{core,web,webdriverio,assertions,console-reporter,serenity-bdd} --save-dev ``` ``` yarn add @serenity-js/{core,web,webdriverio,assertions,console-reporter,serenity-bdd} --dev ``` ``` pnpm add @serenity-js/{core,web,webdriverio,assertions,console-reporter,serenity-bdd} --save-dev ``` ``` bun add @serenity-js/{core,web,webdriverio,assertions,console-reporter,serenity-bdd} --dev ``` Learn more about Serenity/JS modules: * [`@serenity-js/core`](https://serenity-js.org/api/core/?pk_campaign=wdio8\&pk_source=webdriver.io) * [`@serenity-js/web`](https://serenity-js.org/api/web/?pk_campaign=wdio8\&pk_source=webdriver.io) * [`@serenity-js/webdriverio`](https://serenity-js.org/api/webdriverio/?pk_campaign=wdio8\&pk_source=webdriver.io) * [`@serenity-js/assertions`](https://serenity-js.org/api/assertions/?pk_campaign=wdio8\&pk_source=webdriver.io) * [`@serenity-js/console-reporter`](https://serenity-js.org/api/console-reporter/?pk_campaign=wdio8\&pk_source=webdriver.io) * [`@serenity-js/serenity-bdd`](https://serenity-js.org/api/serenity-bdd/?pk_campaign=wdio8\&pk_source=webdriver.io) ### Configuring Serenity/JS[​](#configuring-serenityjs "Direct link to Configuring Serenity/JS") To enable integration with Serenity/JS, configure WebdriverIO as follows: * TypeScript * JavaScript wdio.conf.ts ``` import { WebdriverIOConfig } from '@serenity-js/webdriverio'; export const config: WebdriverIOConfig = { // Tell WebdriverIO to use Serenity/JS framework framework: '@serenity-js/webdriverio', // Serenity/JS configuration serenity: { // Configure Serenity/JS to use the appropriate adapter for your test runner runner: 'cucumber', // runner: 'mocha', // runner: 'jasmine', // Register Serenity/JS reporting services, a.k.a. the "stage crew" crew: [ // Optional, print test execution results to standard output '@serenity-js/console-reporter', // Optional, produce Serenity BDD reports and living documentation (HTML) '@serenity-js/serenity-bdd', [ '@serenity-js/core:ArtifactArchiver', { outputDirectory: 'target/site/serenity' } ], // Optional, automatically capture screenshots upon interaction failure [ '@serenity-js/web:Photographer', { strategy: 'TakePhotosOfFailures' } ], ] }, // Configure your Cucumber runner cucumberOpts: { // see Cucumber configuration options below }, // ... or Jasmine runner jasmineOpts: { // see Jasmine configuration options below }, // ... or Mocha runner mochaOpts: { // see Mocha configuration options below }, runner: 'local', // Any other WebdriverIO configuration }; ``` wdio.conf.js ``` export const config = { // Tell WebdriverIO to use Serenity/JS framework framework: '@serenity-js/webdriverio', // Serenity/JS configuration serenity: { // Configure Serenity/JS to use the appropriate adapter for your test runner runner: 'cucumber', // runner: 'mocha', // runner: 'jasmine', // Register Serenity/JS reporting services, a.k.a. the "stage crew" crew: [ '@serenity-js/console-reporter', '@serenity-js/serenity-bdd', [ '@serenity-js/core:ArtifactArchiver', { outputDirectory: 'target/site/serenity' } ], [ '@serenity-js/web:Photographer', { strategy: 'TakePhotosOfFailures' } ], ] }, // Configure your Cucumber runner cucumberOpts: { // see Cucumber configuration options below }, // ... or Jasmine runner jasmineOpts: { // see Jasmine configuration options below }, // ... or Mocha runner mochaOpts: { // see Mocha configuration options below }, runner: 'local', // Any other WebdriverIO configuration }; ``` Learn more about: * [Serenity/JS Cucumber configuration options](https://serenity-js.org/api/cucumber-adapter/interface/CucumberConfig/?pk_campaign=wdio8\&pk_source=webdriver.io) * [Serenity/JS Jasmine configuration options](https://serenity-js.org/api/jasmine-adapter/interface/JasmineConfig/?pk_campaign=wdio8\&pk_source=webdriver.io) * [Serenity/JS Mocha configuration options](https://serenity-js.org/api/mocha-adapter/interface/MochaConfig/?pk_campaign=wdio8\&pk_source=webdriver.io) * [WebdriverIO configuration file](/docs/configurationfile.md) ### Producing Serenity BDD reports and living documentation[​](#producing-serenity-bdd-reports-and-living-documentation "Direct link to Producing Serenity BDD reports and living documentation") [Serenity BDD reports and living documentation](https://serenity-bdd.github.io/docs/reporting/the_serenity_reports) are generated by [Serenity BDD CLI](https://github.com/serenity-bdd/serenity-core/tree/main/serenity-cli), a Java program downloaded and managed by the [`@serenity-js/serenity-bdd`](https://serenity-js.org/api/serenity-bdd/?pk_campaign=wdio8\&pk_source=webdriver.io) module. To produce Serenity BDD reports, your test suite must: * download the Serenity BDD CLI, by calling `serenity-bdd update` which caches the CLI `jar` locally * produce intermediate Serenity BDD `.json` reports, by registering [`SerenityBDDReporter`](https://serenity-js.org/api/serenity-bdd/class/SerenityBDDReporter/?pk_campaign=wdio8\&pk_source=webdriver.io) as per the [configuration instructions](#configuring-serenityjs) * invoke the Serenity BDD CLI when you want to produce the report, by calling `serenity-bdd run` The pattern used by all the [Serenity/JS Project Templates](https://serenity-js.org/handbook/project-templates/?pk_campaign=wdio8\&pk_source=webdriver.io#webdriverio) relies on using: * a [`postinstall`](https://docs.npmjs.com/cli/v9/using-npm/scripts#life-cycle-operation-order) NPM script to download the Serenity BDD CLI * [`npm-failsafe`](https://www.npmjs.com/package/npm-failsafe) to run the reporting process even if the test suite itself has failed (which is precisely when you need test reports the most...). * [`rimraf`](https://www.npmjs.com/package/rimraf) as a convenience method to remove any test reports left over from the previous run package.json ``` { "scripts": { "postinstall": "serenity-bdd update", "clean": "rimraf target", "test": "failsafe clean test:execute test:report", "test:execute": "wdio wdio.conf.ts", "test:report": "serenity-bdd run" } } ``` To learn more about the `SerenityBDDReporter`, please consult: * installation instructions in [`@serenity-js/serenity-bdd` documentation](https://serenity-js.org/api/serenity-bdd/?pk_campaign=wdio8\&pk_source=webdriver.io), * configuration examples in [`SerenityBDDReporter` API docs](https://serenity-js.org/api/serenity-bdd/class/SerenityBDDReporter/?pk_campaign=wdio8\&pk_source=webdriver.io), * [Serenity/JS examples on GitHub](https://github.com/serenity-js/serenity-js/tree/main/examples). ### Using Serenity/JS Screenplay Pattern APIs[​](#using-serenityjs-screenplay-pattern-apis "Direct link to Using Serenity/JS Screenplay Pattern APIs") The [Screenplay Pattern](https://serenity-js.org/handbook/design/screenplay-pattern/?pk_campaign=wdio8\&pk_source=webdriver.io) is an innovative, user-centred approach to writing high-quality automated acceptance tests. It steers you towards an effective use of layers of abstraction, helps your test scenarios capture the business vernacular of your domain, and encourages good testing and software engineering habits on your team. By default, when you register `@serenity-js/webdriverio` as your WebdriverIO `framework`, Serenity/JS configures a default [cast](https://serenity-js.org/api/core/class/Cast/?pk_campaign=wdio8\&pk_source=webdriver.io) of [actors](https://serenity-js.org/api/core/class/Actor/?pk_campaign=wdio8\&pk_source=webdriver.io), where every actor can: * [`BrowseTheWebWithWebdriverIO`](https://serenity-js.org/api/webdriverio/class/BrowseTheWebWithWebdriverIO/?pk_campaign=wdio8\&pk_source=webdriver.io) * [`TakeNotes.usingAnEmptyNotepad()`](https://serenity-js.org/api/core/class/TakeNotes/?pk_campaign=wdio8\&pk_source=webdriver.io) This should be enough to help you get started with introducing test scenarios that follow the Screenplay Pattern even to an existing test suite, for example: specs/example.spec.ts ``` import { actorCalled } from '@serenity-js/core' import { Navigate, Page } from '@serenity-js/web' import { Ensure, equals } from '@serenity-js/assertions' describe('My awesome website', () => { it('can have test scenarios that follow the Screenplay Pattern', async () => { await actorCalled('Alice').attemptsTo( Navigate.to(`https://webdriver.io`), Ensure.that( Page.current().title(), equals(`WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO`) ), ) }) it('can have non-Screenplay scenarios too', async () => { await browser.url('https://webdriver.io') await expect(browser) .toHaveTitle('WebdriverIO · Next-gen browser and mobile automation test framework for Node.js | WebdriverIO') }) }) ``` To learn more about the Screenplay Pattern, check out: * [The Screenplay Pattern](https://serenity-js.org/handbook/design/screenplay-pattern/?pk_campaign=wdio8\&pk_source=webdriver.io) * [Web testing with Serenity/JS](https://serenity-js.org/handbook/web-testing/?pk_campaign=wdio8\&pk_source=webdriver.io) * ["BDD in Action, Second Edition"](https://www.manning.com/books/bdd-in-action-second-edition) --- Source: https://webdriver.io/docs/typescript.md # TypeScript Setup You can write tests using [TypeScript](http://www.typescriptlang.org) to get auto-completion and type safety. You will need [`tsx`](https://github.com/privatenumber/tsx) installed in `devDependencies`, via: * npm * Yarn * pnpm * Bun ``` $ npm install tsx --save-dev ``` ``` $ yarn add tsx --dev ``` ``` $ pnpm add tsx --save-dev ``` ``` $ bun add tsx --dev ``` WebdriverIO will automatically detect if these dependencies are installed and will compile your config and tests for you. Ensure to have a `tsconfig.json` in the same directory as your WDIO config. #### Custom TSConfig[​](#custom-tsconfig "Direct link to Custom TSConfig") If you need to set a different path for `tsconfig.json` please set the TSCONFIG\_PATH environment variable with your desired path, or use wdio config's [tsConfigPath setting](/docs/configurationfile.md). Alternatively, you can use the [environment variable](https://tsx.is/dev-api/node-cli#custom-tsconfig-json-path) for `tsx`. #### Type Checking[​](#type-checking "Direct link to Type Checking") Note that `tsx` does not support type-checking - if you wish to check your types then you will need to do this in a separate step with `tsc`. ## Framework Setup[​](#framework-setup "Direct link to Framework Setup") Your `tsconfig.json` needs the following: tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types"] } } ``` Please avoid importing `webdriverio` or `@wdio/sync` explicitly. `WebdriverIO` and `WebDriver` types are accessible from anywhere once added to `types` in `tsconfig.json`. If you use additional WebdriverIO services, plugins or the `devtools` automation package, please also add them to the `types` list as many provide additional typings. ## Framework Types[​](#framework-types "Direct link to Framework Types") Depending on the framework you use, you will need to add the types for that framework to your `tsconfig.json` types property, as well as install its type definitions. This is especially important if you want to have type support for the built-in assertion library [`expect-webdriverio`](https://www.npmjs.com/package/expect-webdriverio). For instance, if you decide to use the Mocha framework, you need to install `@types/mocha` and add it like this to have all types globally available: * Mocha * Jasmine * Cucumber tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types", "@wdio/mocha-framework"] } } ``` tsconfig.json ``` { "compilerOptions": { "types": ["node", "jasmine", "@wdio/globals/types", "@wdio/jasmine-framework"] } } ``` `jasmine` loads `@types/jasmine`, which gives `jasmine`, `spyOn` and `expectAsync`. With `@wdio/jasmine-framework`, the global `expect` returns `void` for Jasmine sync matchers and a `Promise` for WebdriverIO matchers and Jasmine async matchers. `expectAsync` also has the WebdriverIO matchers. The `expect` export of `expect-webdriverio` keeps its Jest matchers. tsconfig.json ``` { "compilerOptions": { "types": ["node", "@wdio/globals/types", "@wdio/cucumber-framework"] } } ``` ## Services[​](#services "Direct link to Services") If you use services that add commands to the browser scope you also need to include these into your `tsconfig.json`. For example if you use the `@wdio/lighthouse-service` ensure that you add it to the `types` as well, e.g.: tsconfig.json ``` { "compilerOptions": { "types": [ "node", "@wdio/globals/types", "@wdio/mocha-framework", "@wdio/lighthouse-service" ] } } ``` Adding services and reporters to your TypeScript config also strengthen the type safety of your WebdriverIO config file. ## Type Definitions[​](#type-definitions "Direct link to Type Definitions") When running WebdriverIO commands all properties are usually typed so that you don't have to deal with importing additional types. However there are cases where you want to define variables upfront. To ensure that these are type safe you can use all types defined in the [`@wdio/types`](https://www.npmjs.com/package/@wdio/types) package. For example if you like to define the remote option for `webdriverio` you can do: ``` import type { Options } from '@wdio/types' // Here is an example where you might want to import the types directly const remoteConfig: Options.WebdriverIO = { hostname: 'http://localhost', port: '4444' // Error: Type 'string' is not assignable to type 'number'.ts(2322) capabilities: { browserName: 'chrome' } } // For other cases, you can use the `WebdriverIO` namespace export const config: WebdriverIO.Config = { ...remoteConfig // Other configs options } ``` ## Tips and Hints[​](#tips-and-hints "Direct link to Tips and Hints") ### Compile & Lint[​](#compile--lint "Direct link to Compile & Lint") To be entirely safe, you may consider following the best practices: compile your code with TypeScript compiler (run `tsc` or `npx tsc`) and have [eslint](https://www.npmjs.com/package/@typescript-eslint/eslint-plugin) running on [pre-commit hook](https://github.com/typicode/husky). --- Source: https://webdriver.io/docs/headless-and-display-servers.md # Headless & Display Servers On Linux, when no display is available, the testrunner starts a virtual display server for the run: [Weston](https://gitlab.freedesktop.org/wayland/weston) in headless mode, or [Xvfb](https://xorg.freedesktop.org/archive/current/doc/man/man1/Xvfb.1.xhtml) (X Virtual Framebuffer) as a fallback. This page covers when that happens, how to configure it, and how it behaves in CI and Docker. In most setups, all you need is Weston or Xvfb installed in your image, or `displayServerAutoInstall: true` in your config. ## When to use a virtual display vs native headless[​](#when-to-use-a-virtual-display-vs-native-headless "Direct link to When to use a virtual display vs native headless") The virtual display gives browsers and apps a screen where there is none, such as on CI runners and in containers. Keep it when: * You test desktop apps, which need a real window. * Your tests need a headed browser, for example to match screenshot baselines taken with a visible browser. * Chrome fails to start with `DevToolsActivePort file doesn't exist` or `user data directory is already in use`, as described in [Troubleshooting](#troubleshooting). For browser tests that don't need a visible window, native headless mode, such as Chrome's `--headless=new`, has less overhead. Set `displayServerEnabled: false` with it, or the testrunner still starts a display server. Do the same when all your browsers run on a cloud service or a remote grid, since nothing local needs a display. ## How it works[​](#how-it-works "Direct link to How it works") The testrunner starts one display server before any service's `onPrepare` hook and sets its environment on `process.env`: | Variable | Weston | Xvfb | | ----------------------------------------------------------------- | -------------------------------------------- | ------------------------------------ | | `WAYLAND_DISPLAY` | `wayland-0` | not set | | `DISPLAY` | not set | the first free display, such as `:0` | | `XDG_RUNTIME_DIR` | a private directory under `/tmp` for the run | unchanged | | `XDG_SESSION_TYPE`, `GDK_BACKEND`, `ELECTRON_OZONE_PLATFORM_HINT` | `wayland` | `x11` | Workers inherit these variables, and so do drivers and apps that services start in `onPrepare`. Browsers and GUI toolkits pick Wayland or X11 from them. Under Weston, the private `XDG_RUNTIME_DIR` replaces any value you had for the run. The display server keeps running until the `onComplete` hooks finish, so services can still use it while they tear down. The testrunner then stops it and restores the previous values. If the process exits earlier, including on Ctrl+C, the display server is killed with it. The testrunner only starts a display server when all of these are true: * It runs on Linux. * Neither `DISPLAY` nor `WAYLAND_DISPLAY` is set. * `displayServerEnabled` is not `false`. If a display already exists, the testrunner uses it and starts nothing. With only `WAYLAND_DISPLAY` set, for example by a Weston your CI starts, the testrunner still sets `XDG_SESSION_TYPE`, `GDK_BACKEND` and `ELECTRON_OZONE_PLATFORM_HINT` to `wayland` for the run. This ensures browsers use the correct display by overriding inherited values, such as `XDG_SESSION_TYPE=tty` from an SSH login, that would send them to X11, where there is no server. It does this even with `displayServerEnabled: false`, which only controls whether a display server starts. ### Which display server is used[​](#which-display-server-is-used "Direct link to Which display server is used") With the default `displayServer: 'auto'`, the testrunner tries Weston first and Xvfb second. Installed servers are tried before anything is installed, so an existing Xvfb is used instead of installing Weston. If Weston fails to start, the testrunner falls back to Xvfb. If no display server starts, the testrunner logs a warning and the run continues without one. With `displayServer: 'wayland'` or `displayServer: 'xvfb'`, the testrunner only tries that server. Weston 10 and later are supported. Ubuntu 22.04 and Debian 11 ship Weston 9, and Enterprise Linux 9 with EPEL enabled gets Weston 8, so set `displayServer: 'xvfb'` there. Weston starts without Xwayland, so it provides no `DISPLAY`. If your tests or tools need X11, for example `xdotool`, `xclip` or a Java app, set `displayServer: 'xvfb'`. ### Window focus[​](#window-focus "Direct link to Window focus") All workers use the same display. In WebdriverIO v9, each worker was wrapped in `xvfb-run` and got a display of its own, so its browser always had focus. Chromium-based browsers such as Chrome and Edge can now lack focus: under Weston no window gets focus, and under Xvfb only the most recently opened window has it. WebDriver input still reaches the page, but `document.hasFocus()` returns `false`, `focus` events don't fire and `:focus` styles don't apply. If your tests depend on focus, turn on focus emulation, an experimental Chrome DevTools Protocol (CDP) command that persists across page loads: wdio.conf.ts ``` export const config: WebdriverIO.Config = { // ... before: async () => { if (browser.isChromium) { await browser.sendCommandAndGetResult('Emulation.setFocusEmulationEnabled', { enabled: true }) } } } ``` Firefox isn't affected, since under WebDriver it treats its pages as focused. ### Standalone scripts[​](#standalone-scripts "Direct link to Standalone scripts") The testrunner starts the display server itself. A standalone script that calls `remote()` can start one with `startDisplayDaemonFromConfig` from `@wdio/display-server`. It takes the same `displayServer*` options, sets the display's variables on `process.env` so the browser inherits them, and restores them on `stop()`: standalone.ts ``` import { remote } from 'webdriverio' import { startDisplayDaemonFromConfig } from '@wdio/display-server' // null off Linux, when an X11 display already exists, or when none starts. With an existing // Wayland display, it returns a handle whose stop() restores the session variables it set. const display = await startDisplayDaemonFromConfig({ displayServerAutoInstall: true }) try { const browser = await remote({ capabilities: { browserName: 'chrome' } }) // ... await browser.deleteSession() } finally { await display?.stop() } ``` You can also run the script under `xvfb-run`, as in [Using an existing display](#using-an-existing-display). ## Browser setup[​](#browser-setup "Direct link to Browser setup") ### Browsers WebdriverIO launches[​](#browsers-webdriverio-launches "Direct link to Browsers WebdriverIO launches") These browsers need no configuration: * Chrome and Edge 140 and later, and Chrome for Testing 135 and later, follow the `XDG_SESSION_TYPE=wayland` that the display server sets. * Older Chrome and Edge ignore `XDG_SESSION_TYPE`. For them, WebdriverIO adds `--ozone-platform=wayland` to the args of every Chrome and Edge it launches while Wayland is up without an X server, unless the args already set `--ozone-platform` or `--headless`. * Electron apps: Electron 38 and later follow `XDG_SESSION_TYPE`, and Electron 28 to 37 follow `ELECTRON_OZONE_PLATFORM_HINT`, which the display server also sets. Electron 27 and earlier rely on the `--ozone-platform=wayland` flag, which WebdriverIO adds when it starts the app through Chromedriver. * Firefox and GTK apps, such as Tauri apps, pick Wayland from `WAYLAND_DISPLAY` and `GDK_BACKEND`. Firefox before 120 is untested. ### Browsers WebdriverIO doesn't launch[​](#browsers-webdriverio-doesnt-launch "Direct link to Browsers WebdriverIO doesn't launch") Browsers on a grid or cloud service need no configuration, since they run on the remote host's display. Local browsers that something else launches, such as a driver you started, an Appium server or a service's own launcher, don't get WebdriverIO's `--ozone-platform=wayland` flag. Chrome and Edge 140 and later, and Electron 28 and later, don't need it, since they follow the session variables, but older Chrome and Edge do. What to do depends on when the browser starts: * **During the run**, for example from a service's `onPrepare`, newer browsers need nothing, since they inherit the display and the session variables. For older Chrome and Edge, either: * set `displayServer: 'xvfb'` to use Xvfb, or * set `displayServer: 'wayland'` and add `--ozone-platform=wayland` to their args to use Weston. * **Before WebdriverIO**, for example from an earlier CI step or another shell, they can't use a display server that WebdriverIO starts, since they don't inherit its variables. Start the display yourself, as in [Using an existing display](#using-an-existing-display), and either: * use Xvfb, which needs nothing more, or * use Weston, then export `XDG_SESSION_TYPE=wayland` (Chrome and Edge 140 and later, Electron 38 and later) or `ELECTRON_OZONE_PLATFORM_HINT=wayland` (Electron 28 to 37), and add `--ozone-platform=wayland` to the args of older Chrome and Edge. ## Configuration[​](#configuration "Direct link to Configuration") All options are listed in the [configuration reference](/docs/configuration.md#displayserverenabled). For example: wdio.conf.ts ``` export const config: WebdriverIO.Config = { // ... // Install a display server if none is installed displayServerAutoInstall: true } ``` wdio.conf.ts ``` export const config: WebdriverIO.Config = { // ... // Always use Xvfb at a smaller size, installed by a custom command that assumes a root container displayServer: 'xvfb', displayServerAutoInstall: true, displayServerAutoInstallCommand: 'apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y xvfb', displayServerWidth: 1280, displayServerHeight: 720 } ``` The custom command is shared by both servers. With `displayServer: '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 your command installs, as this example does. The v9 options `autoXvfb` and `xvfb*` are deprecated and will be removed in v11. See the [v10 migration guide](/docs/v10-migration.md#virtual-displays-on-linux) for their replacements. ## CI and Docker[​](#ci-and-docker "Direct link to CI and Docker") Preinstall a display server in your image, or set `displayServerAutoInstall: true` to install one when the run starts. ### Preinstalling a display server[​](#preinstalling-a-display-server "Direct link to Preinstalling a display server") #### Weston[​](#weston "Direct link to Weston") On Ubuntu 24.04 or Debian 12 and later: ``` RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y weston ``` On RHEL 10 and Oracle Linux 10, enable EPEL and CodeReady Builder yourself, following the [EPEL documentation](https://docs.fedoraproject.org/en-US/epel/getting-started/), then install `weston`. To wrap the testrunner in a Weston of your own, as in [Using an existing display](#using-an-existing-display), also install `xwayland-run`. It's packaged for Debian 13, Ubuntu 24.04, Fedora and openSUSE Tumbleweed. Without it, you need to start Weston in the background with its own `XDG_RUNTIME_DIR` and `WAYLAND_DISPLAY`, and wait for its socket before starting WebdriverIO. Alternatively, use Xvfb. #### Xvfb[​](#xvfb "Direct link to Xvfb") On Ubuntu or Debian: ``` RUN apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y xvfb ``` Ubuntu 22.04 and Debian 11 ship a Weston that's too old, so use Xvfb there. With only Xvfb installed, the testrunner uses it without further configuration. For other distributions, use the package names in [Automatic installation support](#automatic-installation-support). ### Using an existing display[​](#using-an-existing-display "Direct link to Using an existing display") If your CI already provides a display, the testrunner uses it and starts nothing. To use Weston, wrap the testrunner with `wlheadless-run` from the `xwayland-run` package. It gives Weston a private runtime directory and waits for its socket, and the flags match the Weston the testrunner starts: ``` wlheadless-run -c weston --renderer=pixman --idle-time=0 -- npx wdio run wdio.conf.ts ``` To use Xvfb, wrap the testrunner with `xvfb-run`: ``` xvfb-run -a npx wdio run wdio.conf.ts ``` ## Automatic installation support[​](#automatic-installation-support "Direct link to Automatic installation support") `displayServerAutoInstall` works with the package managers below. Installs are non-interactive and time out after 240 seconds. With any other package manager, install the display server yourself. | Package manager | Distributions | Weston | Xvfb | | --------------- | --------------------------------------------------- | --------------------------------------------------------- | ---------------------- | | `apt-get` | Ubuntu, Debian | `weston` | `xvfb` | | `dnf` | Fedora, CentOS Stream, RHEL, Rocky Linux, AlmaLinux | `weston` | `xorg-x11-server-Xvfb` | | `zypper` | openSUSE, SUSE Linux Enterprise | `weston` | `xvfb-run` | | `pacman` | Arch Linux, Manjaro | `weston` | `xorg-server-xvfb` | | `apk` | Alpine Linux | `weston` `weston-backend-headless` `weston-shell-desktop` | `xvfb-run` | | `xbps-install` | Void Linux | `weston` | `xvfb-run` | * On Arch Linux, the install runs `pacman -Syu`, a full system upgrade, since Arch doesn't support partial upgrades. On an outdated image this can exceed the 240-second limit, so preinstall the display server there. * Enterprise Linux 10 has no Xvfb and ships Weston only in EPEL, which needs CRB. On CentOS Stream, AlmaLinux and Rocky Linux, the install enables both and leaves them enabled. On RHEL and Oracle Linux, set them up yourself, as in [Preinstalling a display server](#preinstalling-a-display-server). ## Logs[​](#logs "Direct link to Logs") The display server runs in the launcher process, so its messages are in the launcher log: `wdio.log` in your `outputDir`, or the terminal if `outputDir` isn't set. The log shows which display server started and the variables it set. For more detail, raise its log level: wdio.conf.ts ``` export const config: WebdriverIO.Config = { // ... outputDir: './logs', logLevels: { '@wdio/display-server': 'debug' } } ``` ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### Chrome fails with `DevToolsActivePort file doesn't exist`[​](#chrome-fails-with-devtoolsactiveport-file-doesnt-exist "Direct link to chrome-fails-with-devtoolsactiveport-file-doesnt-exist") The full message is `Chrome failed to start: exited abnormally. (DevToolsActivePort file doesn't exist)`. A common cause is a headed Chrome with no display to open its window on. Check the [launcher log](#logs) for the display server that started. If none did, see [The launcher log shows `No display server could be started`](#the-launcher-log-shows-no-display-server-could-be-started). If your tests don't need a visible window, use native headless mode instead, as in [When to use a virtual display vs native headless](#when-to-use-a-virtual-display-vs-native-headless). ### Chrome fails with `user data directory is already in use`[​](#chrome-fails-with-user-data-directory-is-already-in-use "Direct link to chrome-fails-with-user-data-directory-is-already-in-use") The full message starts with `session not created: probably user data directory is already in use`. It is often misleading: it usually means the browser crashed and restarted with the previous instance's profile directory. A stable display often resolves it. If not, pass a unique `--user-data-dir` per session. Without a `--user-data-dir`, ChromeDriver uses a new temporary profile for each session. WebdriverIO never changes or deletes a `--user-data-dir` that you set, so set one to keep a profile. ### The launcher log shows `No display server could be started`[​](#the-launcher-log-shows-no-display-server-could-be-started "Direct link to the-launcher-log-shows-no-display-server-could-be-started") The full message is `No display server could be started; continuing without a virtual display`. No display server is installed, or none started. The messages before it say why: * `wayland not found. To enable auto-install, set 'displayServerAutoInstall: true' in your WDIO config.` or `xvfb not found. To enable auto-install, set 'displayServerAutoInstall: true' in your WDIO config.`: nothing is installed and auto-install is off. * `wayland failed to start: ...` or `xvfb failed to start: ...`: the server's error output follows. * `Failed to install Weston` or `Failed to install Xvfb`: the install failed. * `wayland still not found after installing` or `xvfb still not found after installing`: the install succeeded but didn't provide that server, for example because a custom `displayServerAutoInstallCommand` installs only the other one. Set `displayServer` to the server your command installs. Install Weston or Xvfb in your image, or set `displayServerAutoInstall: true`. ### Xvfb exits with `Failed to find a socket to listen on`[​](#xvfb-exits-with-failed-to-find-a-socket-to-listen-on "Direct link to xvfb-exits-with-failed-to-find-a-socket-to-listen-on") Xvfb creates its socket in `/tmp/.X11-unix`. If that directory exists, it must be writable by the test user, as mode `1777` is. ### Chrome or Electron fails under Weston with `Missing X server or $DISPLAY`[​](#chrome-or-electron-fails-under-weston-with-missing-x-server-or-display "Direct link to chrome-or-electron-fails-under-weston-with-missing-x-server-or-display") The browser tried X11 instead of Wayland. If WebdriverIO didn't launch it, see [Browsers WebdriverIO doesn't launch](#browsers-webdriverio-doesnt-launch). Otherwise, remove `--ozone-platform=x11` from its args. ### Focus-dependent tests fail in Chrome or Edge[​](#focus-dependent-tests-fail-in-chrome-or-edge "Direct link to Focus-dependent tests fail in Chrome or Edge") `document.hasFocus()` returns `false` because pages on the shared display can lack focus. Turn on focus emulation, as in [Window focus](#window-focus). ### An X11 tool or app fails under Weston with `cannot open display` or `Can't open display`[​](#an-x11-tool-or-app-fails-under-weston-with-cannot-open-display-or-cant-open-display "Direct link to an-x11-tool-or-app-fails-under-weston-with-cannot-open-display-or-cant-open-display") Weston provides no `DISPLAY`. Set `displayServer: 'xvfb'` so the testrunner starts Xvfb instead. If you started Weston yourself, wrap the run with `xvfb-run`, since the testrunner uses an existing display rather than starting one. ## Next steps[​](#next-steps "Direct link to Next steps") * [Configuration](/docs/configuration.md#displayserverenabled) reference for every `displayServer*` option. * [v10 migration guide](/docs/v10-migration.md#virtual-displays-on-linux) for the replacements of the v9 options `autoXvfb` and `xvfb*`. * [Docker](/docs/docker.md) and [GitHub Actions](/docs/githubactions.md) to run your suite in CI. * [Desktop Apps](/docs/platforms/desktop.md#linux) for Electron, Tauri and Dioxus on Linux. --- Source: https://webdriver.io/docs/parallel-tests.md # Parallel Tests in a Spec File Since v10, WebdriverIO can run the tests of one spec file at the same time. Every Mocha `it()` or Cucumber scenario gets its own browser window (a WebDriver BiDi [browsing context](https://w3c.github.io/webdriver-bidi/#browsing-context)) in one worker and one browser session. Use it for spec files with many independent tests: they finish faster, and you don't need more worker processes or browser sessions, because each test only pays for opening a window. It is a form of browser pooling: the tests share a pool of windows in one browser, not a pool of browsers. If you come from Playwright, `parallelMode: 'userContexts'` is the closest equivalent of [`fullyParallel: true`](https://playwright.dev/docs/test-parallel#parallelize-tests-in-a-single-file): every test gets its own isolated context. The difference is that Playwright spreads the tests of a file across worker processes, each with its own browser, while WebdriverIO runs them at the same time in one worker and one browser. This is separate from [`maxInstances`](/docs/organizingsuites.md), which runs whole spec files in parallel, one worker and one session per spec. You can combine the two: `maxInstances` sets how many spec files run at the same time, and `maxParallelContexts` sets how many tests run at the same time inside each of those files. Experimental Parallel mode requires the experimental `'wdio:experimentalBiDiCommands'` capability, which changes how element commands are implemented in every test, not only parallel ones. See [Behavior changes of the BiDi element commands](#behavior-changes-of-the-bidi-element-commands). ## Enable parallel mode[​](#enable-parallel-mode "Direct link to Enable parallel mode") You need: * a WebDriver BiDi session (the default, unless you set `'wdio:enforceWebDriverClassic': true`), * the `'wdio:experimentalBiDiCommands': true` capability, * `@wdio/mocha-framework` or `@wdio/cucumber-framework`. Jasmine does not support parallel mode. If the session does not use BiDi, or the capability is missing, WebdriverIO logs a warning and runs the tests one after another. Without `parallelMode`, nothing changes. ### Mocha[​](#mocha "Direct link to Mocha") wdio.conf.ts ``` export const config: WebdriverIO.Config = { specs: ['./test/specs/**/*.e2e.ts'], maxInstances: 1, capabilities: [{ browserName: 'chrome', 'wdio:experimentalBiDiCommands': true }], framework: 'mocha', mochaOpts: { ui: 'bdd', timeout: 60000, parallelMode: 'contexts', maxParallelContexts: 4 } } ``` The spec file needs no changes: test/specs/pages.e2e.ts ``` import { browser, $, expect } from '@wdio/globals' describe('webdriver.io', () => { it('shows the API page', async () => { await browser.url('https://webdriver.io/docs/api') await expect($('h1')).toHaveText('Introduction') }) it('shows the getting started page', async () => { await browser.url('https://webdriver.io/docs/gettingstarted') await expect($('h1')).toHaveText('Getting Started') }) }) ``` Both tests run at the same time, each in its own window. `browser.url()`, `$()` and `expect()` act on the window of the test that calls them. ### Cucumber[​](#cucumber "Direct link to Cucumber") wdio.conf.ts ``` export const config: WebdriverIO.Config = { specs: ['./features/**/*.feature'], capabilities: [{ browserName: 'chrome', 'wdio:experimentalBiDiCommands': true }], framework: 'cucumber', cucumberOpts: { require: ['./features/step-definitions/**/*.ts'], parallelMode: 'contexts', maxParallelContexts: 4 } } ``` Every scenario of a feature file runs in its own window. Profiles (`cucumberOpts.profiles`, `cucumberOpts.file`), specs with line numbers (`--spec ./features/login.feature:5`) and the `tags`, `name`, `order`, `strict`, `dryRun`, `failFast`, `retry` and `retryTagFilter` options work like in a sequential run. Features, scenarios, steps and hooks are reported like in a sequential run, also with `ignoreUndefinedDefinitions`, `failAmbiguousDefinitions`, `tagsInTitle` and `scenarioLevelReporter`. ## Options[​](#options "Direct link to Options") | Option | Values | Default | Description | | --------------------- | ------------------------------ | -------------------- | ------------------------------------------------------ | | `parallelMode` | `'contexts'`, `'userContexts'` | not set (sequential) | Turns on parallel mode and picks how much tests share. | | `maxParallelContexts` | number | `os.cpus().length` | How many tests run at the same time. | Set both in `mochaOpts` or in `cucumberOpts`. `maxParallelContexts` sets the number of slots. Each slot runs one test at a time, opens the window for its next test while the current test runs, and closes the previous window in the background. Up to 3 × `maxParallelContexts` windows, plus the session's first window, can therefore be open for a short time: each slot can hold one live, one prefetched and one closing window. Parallel mode closes only the windows it opened. ## Choose between `contexts` and `userContexts`[​](#choose-between-contexts-and-usercontexts "Direct link to choose-between-contexts-and-usercontexts") | | `'contexts'` | `'userContexts'` | | ---------------------------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------- | | Window per test | yes | yes | | Cookies, `localStorage`, service workers | shared by all tests | isolated per test ([user context](https://w3c.github.io/webdriver-bidi/#user-context)) | | Login | once, if the tests reuse the session cookie | in every test | | Driver support | any BiDi browser | needs `browser.createUserContext()` support, otherwise the run fails | Pick `'contexts'` by default. Pick `'userContexts'` when tests must not see each other's cookies or storage, for example tests that log in as different users. Like `'contexts'`, `'userContexts'` falls back to a sequential run with a warning when the session is not WebDriver BiDi or `'wdio:experimentalBiDiCommands'` is missing from the capabilities. If the driver does not support `browser.createUserContext`, the run fails rather than falling back. A tab or window that a test opens with `browser.newWindow(url)` opens from the window of the test, so it has the cookies and storage of the test. To open a window outside the test's cookie and storage isolation, create it with `browser.browsingContextCreate()`, and get its browsing context from `browser.browsingContexts()`: ``` const { context } = await browser.browsingContextCreate({ type: 'window' }) await browser.browsingContextNavigate({ context, url: 'https://example.com', wait: 'complete' }) const outside = (await browser.browsingContexts()).find((c) => c.contextId === context) await outside.$('h1').getText() ``` ## What each test owns[​](#what-each-test-owns "Direct link to What each test owns") Inside a parallel test, these commands act on the test's own window: * navigation: `url`, `back`, `forward`, `refresh`, `getUrl`, `getTitle` * element commands: `$`, `$$`, `shadow$`, `click`, `setValue`, `getText`, the `waitFor*` commands, and others * `execute`, `actions`, `addInitScript` * cookies: `getCookies`, `setCookies`, `deleteCookies` use the cookies of the test's window (its user context with `'userContexts'`), as described in [Behavior changes of the BiDi element commands](#behavior-changes-of-the-bidi-element-commands) * `mock()`: a mock created in a parallel test only intercepts and records requests of that test's window and its frames, so two tests can mock the same URL. A test can override a mock of the same URL that `beforeSuite` in `wdio.conf.ts` created: the mock of the test answers in its window, and the `beforeSuite` mock keeps answering in the other windows. Create a default mock in `beforeSuite` and override it in the test, or in a `before()` or `beforeEach()` hook of the spec file. See [Which mock answers a request](/docs/api/mock.md#which-mock-answers-a-request) * `mockClearAll()`, `mockRestoreAll()`: only the mocks that the test created, also in its `before()` hook and on tabs it opened. Mocks created in the `beforeSuite` hook in `wdio.conf.ts`, outside the test windows, stay * screenshots: `saveScreenshot`, `takeElementScreenshot` ## Commands that throw in parallel mode[​](#commands-that-throw-in-parallel-mode "Direct link to Commands that throw in parallel mode") Some commands act on the whole browser or the whole session, so they cannot target a single test's window. Inside a parallel test they throw instead of affecting another test: | Commands | Why | Use instead | | -------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `getWindowSize`, `setWindowSize` | the OS window is shared | use `browser.setViewport()` to size a test's page. Parallel tests share one OS window | | `throttleNetwork`, `throttleCPU` | they apply to the whole browser | run those tests without parallel mode | | `closeWindow`, `switchToParentFrame` | they change the focused window, which all tests share | keep each test in its own window | | `reloadSession`, `setTimeout` | they change the session that all tests share | call them in the `before` hook in `wdio.conf.ts` | | `acceptAlert`, `dismissAlert`, `getAlertText`, `sendAlertText` | alerts belong to a browsing context | call them on the context `browser.url()` returns: `const page = await browser.url('https://webdriver.io'); await page.acceptAlert()`. Use `page.acceptAlert(text)` instead of `sendAlertText(text)`. `dismissAlert()` and `getAlertText()` work on the context too | | `getComputedRole`, `getComputedLabel` | WebDriver BiDi cannot read them | run those tests without parallel mode | `switchWindow` was removed for all WebDriver BiDi sessions in v10, not only in parallel mode. It throws ``switchWindow` was removed for WebDriver BiDi sessions in WebdriverIO v10. Hold the browsing context returned by `browser.url()` or `browser.newWindow()`, or find one with `browser.browsingContexts()`.`` Keep the context object instead of switching to it. WebdriverIO dismisses prompts automatically unless something listens to the `dialog` event, so register a listener (`browser.on('dialog', () => {})`) before you answer a prompt from a test. Every other WebDriver Classic command also throws. Only `status`, `getTimeouts` and `getWindowHandles` are allowed. If a WebdriverIO command falls back to WebDriver Classic in parallel mode without you calling a Classic command, please [report it](https://github.com/webdriverio/webdriverio/issues/new/choose). ## Hooks and timeouts[​](#hooks-and-timeouts "Direct link to Hooks and timeouts") ### Mocha[​](#mocha-1 "Direct link to Mocha") * `before()` and `after()` in a spec file run **once per test**, not once per `describe`, because every test has its own window. Each test runs `before`, `beforeEach`, the test, `afterEach` and `after` in its window. Put setup that should run once per spec file in the `beforeSuite` / `afterSuite` hooks in `wdio.conf.ts`. These run once, outside any test window. * Because each test runs its own hooks, a failing hook only affects its own test. A failing `before()` or `after()` is reported one time for each test, not one time for the `describe`, because parallel mode runs it once for each test. A failing `beforeEach()` or `afterEach()` does not stop the other tests of the `describe`. In a sequential run, Mocha skips them. With `failHookAffectedTests` (the default), the test that a failed `before()` or `beforeEach()` skips fails with the same text as in a sequential run. Only the hook title can differ: a failed `beforeEach()` names the test of its own window (`"before each" hook for "t2"`), while a sequential run names the first test for all of them. * Only `mochaOpts.timeout` applies. `this.timeout()` in a test or hook throws, and `it(...).timeout()` or a `describe` timeout is ignored with a warning. See [Mocha timeouts and the WebdriverIO hooks](/docs/timeouts.md#mocha-timeouts-and-the-webdriverio-hooks). * `mochaOpts.bail` and Mocha retries are not supported and fail the run: `mochaOpts.retries`, `this.retries(n)` in a `describe` and `it(...).retries(n)`. `this.retries()` in a test or hook throws. The [WebdriverIO retries](/docs/retry.md) (`it(title, fn, retries)`) work in parallel mode. * `.only()`, `this.skip()`, `grep`, `fgrep` and `invert` work like in a sequential run. * An error that no test awaits (for example a timer that throws) fails the test or hook of the window it comes from, and the other tests go on. As in a sequential run, an unhandled rejection does not fail a test, and with `mochaOpts.allowUncaught` the error ends the worker. An error that comes after its test ended, while other tests still run, fails the run and is logged, but no test shows it (a sequential run shows it on the test that runs at that time). After the last window closed, such an error ends the worker, as in a sequential run. The same is true for an error from an event emitter that your code made outside a test, and on Node.js 22 for an error from `queueMicrotask()`, because the window of the test is not known there. * `mochaOpts.dryRun`, `forbidPending` and `checkLeaks` do not apply in parallel mode yet: the tests run, a pending test does not fail, and a global leak is not reported. ### Cucumber[​](#cucumber-1 "Direct link to Cucumber") * `BeforeAll` / `AfterAll` and the `beforeFeature` / `afterFeature` hooks in `wdio.conf.ts` run once per worker, not once per feature. A `BeforeAll` / `AfterAll` is reported once, when it starts and when it ends: a `BeforeAll` as a hook of the first feature, an `AfterAll` as a hook of the last feature, as in a sequential run. `beforeFeature` / `afterFeature` receive the uri and feature of the first feature file only, which matters when one worker runs several feature files, for example grouped specs. They run outside any scenario's window, so they must not use commands that need one. * `Before` / `After`, `BeforeStep` / `AfterStep` and the scenario and step hooks in `wdio.conf.ts` run for every scenario, in that scenario's window. * `cucumberOpts.strict` defaults to `true`, as in Cucumber: a pending step fails the run. Set `strict: false` to let it pass. * With `failFast`, the scenarios that already run in other windows finish after the first failure. The scenarios that did not start are reported as skipped, as in a sequential run. * With `ignoreUndefinedDefinitions: true`, an ambiguous step (with `failAmbiguousDefinitions: false`) fails the run. A sequential run then passes. * Cucumber formatters (`format`, `formatOptions`, `publish`) don't run, so they write no file. * An error that no step awaits (for example a timer that throws, or an unhandled rejection) fails the step or hook of the window it comes from, as in a sequential run, and the other scenarios go on. An error that comes after its scenario ended, while other scenarios still run, fails the run and is logged, but no step shows it (a sequential run shows it on the step that runs at that time). The same is true for an error from an event emitter that your code made outside a scenario, and on Node.js 22 for an error from `queueMicrotask()`, because the window of the scenario is not known there. An error in `BeforeAll` / `AfterAll` fails that hook, as in a sequential run. ### Both frameworks[​](#both-frameworks "Direct link to Both frameworks") A test's window closes as soon as the test finishes. Don't start timers or promises that keep running after the test ends. ## Behavior changes of the BiDi element commands[​](#behavior-changes-of-the-bidi-element-commands "Direct link to Behavior changes of the BiDi element commands") `'wdio:experimentalBiDiCommands': true` swaps the implementation of several element commands in every test of the session, sequential or parallel: * `addValue` and `clearValue` dispatch synthetic DOM events, not trusted key events. * `getAttribute` follows the WebDriver rules for property and attribute values. * `click` is sent through the Actions API. * `getCookies`, `setCookies` and `deleteCookies` use the cookie jar of the window (the WebDriver BiDi storage partition of its user context), as Puppeteer does. `getCookies` and `deleteCookies` keep the cookies that the page sees by domain and path, or with a `domain` in the filter the cookies of that domain, whatever page is open. Secure cookies and partitioned (CHIPS) cookies stay in the result, also a cookie of the page host that is partitioned under another top-level site. `setCookies` sends `domain` as given: `example.com` is a host-only cookie, `.example.com` also goes to the subdomains. `getCookies(filter, sourceOrigin)` reads the WebDriver BiDi storage partition of that origin, and `getCookies(filter, null)` all cookies of the window. `sameSite` is lowercase in the result. BiDi errors are not retried with WebDriver Classic. Run your suite once with the capability and without `parallelMode` to find tests that depend on the Classic behavior. ## Reporters[​](#reporters "Direct link to Reporters") Reporters that extend [`@wdio/reporter`](/docs/customreporter.md) report parallel tests under the right suite, and attach a command to the test whose browsing context sent it. `@wdio/allure-reporter` supports parallel mode with Mocha and Cucumber. With Mocha, it writes a test's result when the test and its `afterEach()` and `after()` hooks end. `before()` and `after()` hooks run once per test in parallel mode, so the report shows their fixtures once per test. With Cucumber, each scenario keeps its own result, steps and attachments. `@wdio/spec-reporter` supports parallel mode: each Mocha `describe` block and each Cucumber scenario is shown under its own parent, also when tests run at the same time. `@wdio/cucumberjs-json-reporter` supports parallel mode: each scenario keeps its own steps, hooks, step lines and attachments. An attachment from code that runs outside a scenario, such as the WebdriverIO `after` hook, goes to the scenario that started last. A failed `BeforeAll` or `AfterAll` hook is not in the JSON, because it has no scenario to attach to. `@wdio/html-reporter` supports parallel mode with Mocha and Cucumber. It shows each log, screenshot and video under the test that sent it, also when it comes from a hook or after the test ends. An event from code that runs outside a test, such as an `AfterAll` hook or a `browser.on()` callback (a listener is for the whole session and gets the events of all test windows), goes to the test that started last, and the reporter logs a warning. An event from before the first test (for example the `before` hook of the configuration) goes to the first test that starts. `@wdio/video-reporter` records each parallel test in its own video. With Cucumber, it does not attach the videos to Allure. A custom reporter must not assume that a test ends before the next one starts. See [Reporters and parallel tests](/docs/customreporter.md#reporters-and-parallel-tests). ## Cloud vendors[​](#cloud-vendors "Direct link to Cloud vendors") Cloud vendors record one video, one set of logs and one test status per browser session. In parallel mode, many tests share that session, so the vendor dashboard can't split the video, logs or pass/fail status by test. `userContexts` also needs the vendor's grid to support `browser.createUserContext` (and `browser.removeUserContext` with Mocha). Parallel mode hasn't been tested on any cloud vendor yet. We recommend that you leave parallel mode off when you run on a cloud vendor and use [`maxInstances`](/docs/organizingsuites.md) to run spec files in parallel. To turn it off, remove `parallelMode` from the framework options. If you remove only `'wdio:experimentalBiDiCommands'`, the tests run one after another and every run logs a warning. ## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting") ### `parallelMode: "contexts" requires 'wdio:experimentalBiDiCommands': true to be set in capabilities`[​](#parallelmode-contexts-requires-wdioexperimentalbidicommands-true-to-be-set-in-capabilities "Direct link to parallelmode-contexts-requires-wdioexperimentalbidicommands-true-to-be-set-in-capabilities") Add `'wdio:experimentalBiDiCommands': true` to the capability. Without it, the tests run one after another. With Cucumber, the message reads `Parallel mode (cucumberOpts.parallelMode: "contexts") requires "wdio:experimentalBiDiCommands" to be set in capabilities`. ### `... is set but the browser session does not support WebDriver Bidi`[​](#-is-set-but-the-browser-session-does-not-support-webdriver-bidi "Direct link to -is-set-but-the-browser-session-does-not-support-webdriver-bidi") The session uses WebDriver Classic. Remove `'wdio:enforceWebDriverClassic': true` from the capability, or use a browser and driver with WebDriver BiDi support. With Cucumber, the message reads `Parallel mode (cucumberOpts.parallelMode: "contexts") requires a WebDriver Bidi session. Falling back to sequential execution.` ### `parallelMode: "userContexts" requires browser.createUserContext and browser.removeUserContext, which this driver does not support`[​](#parallelmode-usercontexts-requires-browsercreateusercontext-and-browserremoveusercontext-which-this-driver-does-not-support "Direct link to parallelmode-usercontexts-requires-browsercreateusercontext-and-browserremoveusercontext-which-this-driver-does-not-support") The driver cannot create user contexts. Use `parallelMode: 'contexts'` or update the browser and driver. With Cucumber, the message reads `cucumberOpts.parallelMode "userContexts" requires browser.createUserContext, which this driver does not provide. Use a driver with BiDi user context support or set parallelMode to "contexts" (shares cookies and storage between scenarios).` ### `... is not supported inside parallel mode tests because ...` or `... is not supported in parallel mode`[​](#-is-not-supported-inside-parallel-mode-tests-because--or--is-not-supported-in-parallel-mode "Direct link to -is-not-supported-inside-parallel-mode-tests-because--or--is-not-supported-in-parallel-mode") The test called a command from [Commands that throw in parallel mode](#commands-that-throw-in-parallel-mode). Use the alternative from the table. ### `bail is not supported in parallel mode` / `retries is not supported in parallel mode`[​](#bail-is-not-supported-in-parallel-mode--retries-is-not-supported-in-parallel-mode "Direct link to bail-is-not-supported-in-parallel-mode--retries-is-not-supported-in-parallel-mode") Remove `mochaOpts.bail` or `mochaOpts.retries`, or the `this.retries(n)` / `.retries(n)` of the test that the error names, or run the spec file without `parallelMode`. To retry a test in parallel mode, use the [WebdriverIO retries](/docs/retry.md) (`it(title, fn, retries)`). ### `Suite-level hooks (before()/after()) run once per test in parallel mode`[​](#suite-level-hooks-beforeafter-run-once-per-test-in-parallel-mode "Direct link to suite-level-hooks-beforeafter-run-once-per-test-in-parallel-mode") The spec file has `before()` or `after()` hooks. They run for every test. Move setup that should run only once to `beforeSuite` / `afterSuite` in `wdio.conf.ts`. ## Related pages[​](#related-pages "Direct link to Related pages") * [Organizing Test Suites](/docs/organizingsuites.md): run spec files in parallel with `maxInstances` * [Sharding](/docs/sharding.md): split the suite across machines * [Frameworks](/docs/frameworks.md): all Mocha and Cucumber options * [Automation Protocols](/docs/automationProtocols.md): WebDriver BiDi and WebDriver Classic --- Source: https://webdriver.io/docs/sharding.md # Sharding By default, WebdriverIO runs tests in parallel and strives for optimal utilization of CPU cores on your machine. In order to achieve even greater parallelisation, you can further scale WebdriverIO test execution by running tests on multiple machines simultaneously. We call this mode of operation "sharding". ## Sharding tests between multiple machines[​](#sharding-tests-between-multiple-machines "Direct link to Sharding tests between multiple machines") To shard the test suite, pass `--shard=x/y` to the command line. For example, to split the suite into four shards, each running one fourth of the tests: ``` npx wdio run wdio.conf.js --shard=1/4 npx wdio run wdio.conf.js --shard=2/4 npx wdio run wdio.conf.js --shard=3/4 npx wdio run wdio.conf.js --shard=4/4 ``` Now, if you run these shards in parallel on different computers, your test suite completes four times faster. ## GitHub Actions example[​](#github-actions-example "Direct link to GitHub Actions example") GitHub Actions supports [sharding tests between multiple jobs](https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs) using the [`jobs..strategy.matrix`](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstrategymatrix) option. The matrix option will run a separate job for every possible combination of the provided options. The following example shows you how to configure a job to run your tests on four machines in parallel. You can find the whole pipeline setup in the [Cucumber Boilerplate](https://github.com/webdriverio/cucumber-boilerplate/blob/main/.github/workflows/test.yaml) project. * First we add a matrix option to our job configuration with the shard option containing the number of shards we want to create. `shard: [1, 2, 3, 4]` will create four shards, each with a different shard number. * Then we run our WebdriverIO tests with the `--shard ${{ matrix.shard }}/${{ strategy.job-total }}` option. This will be our test command for each shard. * Finally we upload our wdio log report to the GitHub Actions Artifacts. This will make logs available in case the shard fails. The test pipeline is defined as follows: ``` name: Test on: [push, pull_request] jobs: lint: # ... unit: # ... e2e: name: 🧪 Test (${{ matrix.shard }}/${{ strategy.job-total }}) runs-on: ubuntu-latest needs: [lint, unit] strategy: matrix: shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v4 - uses: ./.github/workflows/actions/setup - name: E2E Test run: npm run test:features -- --shard ${{ matrix.shard }}/${{ strategy.job-total }} - uses: actions/upload-artifact@v1 if: failure() with: name: logs-${{ matrix.shard }} path: logs ``` This will run all shards in parallel, reducing executing time for the tests by 4: ![GitHub Actions example](/assets/images/sharding-ee2dc811d75d1467a4d368baa6bd582e.png "GitHub Actions example") See commit [`96d444e`](https://github.com/webdriverio/cucumber-boilerplate/commit/96d444ea23919389682b9b1c9408ed91c452c7f8) from the [Cucumber Boilerplate](https://github.com/webdriverio/cucumber-boilerplate) project that introduced sharding to its test pipeline which helped reduce the overall execution time from `2:23 min` down to `1:30 min`, a reduction of **37%** 🎉. --- Source: https://webdriver.io/docs/retry.md # Retry Flaky Tests You can rerun certain tests with the WebdriverIO testrunner that turn out to be unstable due to things like a flaky network or race conditions. (However, it is not recommended to simply increase the rerun rate if tests become unstable!) ## Rerun suites in Mocha[​](#rerun-suites-in-mocha "Direct link to Rerun suites in Mocha") Since version 3 of Mocha, you can rerun whole test suites (everything inside an `describe` block). If you use Mocha you should favor this retry mechanism instead of the WebdriverIO implementation that only allows you to rerun certain test blocks (everything within an `it` block). In order to use the `this.retries()` method, the suite block `describe` must use an unbound function `function(){}` instead of a fat arrow function `() => {}`, as described in [Mocha docs](https://mochajs.org/#arrow-functions). Using Mocha you can also set a retry count for all specs using `mochaOpts.retries` in your `wdio.conf.js`. Here is an example: ``` describe('retries', function () { // Retry all tests in this suite up to 4 times this.retries(4) beforeEach(async () => { await browser.url('http://www.yahoo.com') }) it('should succeed on the 3rd try', async function () { // Specify this test to only retry up to 2 times this.retries(2) console.log('run') await expect($('.foo')).toBeDisplayed() }) }) ``` ## Rerun single tests in Jasmine or Mocha[​](#rerun-single-tests-in-jasmine-or-mocha "Direct link to Rerun single tests in Jasmine or Mocha") To rerun a certain test block you can just apply the number of reruns as last parameter after the test block function: * Mocha * Jasmine ``` describe('my flaky app', () => { /** * spec that runs max 4 times (1 actual run + 3 reruns) */ it('should rerun a test at least 3 times', async function () { console.log(this.wdioRetries) // returns number of retries // ... }, 3) }) ``` The same works for hooks too: ``` describe('my flaky app', () => { /** * hook that runs max 2 times (1 actual run + 1 rerun) */ beforeEach(async () => { // ... }, 1) // ... }) ``` ``` describe('my flaky app', () => { /** * spec that runs max 4 times (1 actual run + 3 reruns) */ it('should rerun a test at least 3 times', async function () { console.log(this.wdioRetries) // returns number of retries // ... }, jasmine.DEFAULT_TIMEOUT_INTERVAL, 3) }) ``` The same works for hooks too: ``` describe('my flaky app', () => { /** * hook that runs max 2 times (1 actual run + 1 rerun) */ beforeEach(async () => { // ... }, jasmine.DEFAULT_TIMEOUT_INTERVAL, 1) // ... }) ``` If you are using Jasmine, the second parameter is reserved for timeout. To apply a retry parameter you need to set the timeout to its default value `jasmine.DEFAULT_TIMEOUT_INTERVAL` and then apply your retry count. This retry mechanism only allows to retry single hooks or test blocks. If your test is accompanied with a hook to set up your application, this hook is not being run. [Mocha offers](https://mochajs.org/#retry-tests) native test retries that provide this behavior while Jasmine doesn't. You can access the number of executed retries in the `afterTest` hook. With Mocha, all attempts of a test or hook share its timeout: Mocha starts the timer once, and it fails the test when all attempts together take longer than the timeout. So this mechanism retries a test or hook that fails (for example a failed assertion or command), but not one that hits its timeout, because a later attempt could not finish in time. The timeout error of a test or hook with WebdriverIO retries names the attempt that timed out, for example `(WDIO attempt 2/3)`. For tests that can time out, use [Mocha's retries](https://mochajs.org/#retry-tests) (`this.retries()`): Mocha runs each attempt again with a full timeout. ## Rerunning in Cucumber[​](#rerunning-in-cucumber "Direct link to Rerunning in Cucumber") ### Rerun full suites in Cucumber[​](#rerun-full-suites-in-cucumber "Direct link to Rerun full suites in Cucumber") For cucumber >=6 you can provide the [`retry`](https://github.com/cucumber/cucumber-js/blob/master/docs/cli.md#retry-failing-tests) configuration option along with a `retryTagFilter` optional parameter to have all or some of your failing scenarios get additional retries until succeeded. ### Rerun Step Definitions in Cucumber[​](#rerun-step-definitions-in-cucumber "Direct link to Rerun Step Definitions in Cucumber") To define a rerun rate for a certain step definitions just apply a retry option to it, like: ``` export default function () { /** * step definition that runs max 3 times (1 actual run + 2 reruns) */ this.Given(/^some step definition$/, { wrapperOptions: { retry: 2 } }, async () => { // ... }) // ... }) ``` Reruns can only be defined in your step definitions file, never in your feature file. ## Add retries on a per-specfile basis[​](#add-retries-on-a-per-specfile-basis "Direct link to Add retries on a per-specfile basis") Previously, only test- and suite-level retries were available, which are fine in most cases. But in any tests which involve state (such as on a server or in a database) the state may be left invalid after the first test failure. Any subsequent retries may have no chance of passing, due to the invalid state they would start with. A new `browser` instance is created for each specfile, which makes this an ideal place to hook and setup any other states (server, databases). Retries on this level mean that the whole setup process will simply be repeated, just as if it were for a new specfile. wdio.conf.js ``` export const config = { // ... /** * The number of times to retry the entire specfile when it fails as a whole */ specFileRetries: 1, /** * Delay in seconds between the spec file retry attempts */ specFileRetriesDelay: 0, /** * Retried specfiles are inserted at the beginning of the queue and retried immediately */ specFileRetriesDeferred: false } ``` ## Run a specific test multiple times[​](#run-a-specific-test-multiple-times "Direct link to Run a specific test multiple times") This is to help prevent flaky tests from being introduced in a codebase. By adding the `--repeat` cli option it will run the specified specs or suites N times. When using this cli flag the `--spec` or `--suite` flag must also be specified. When adding new tests to a codebase, especially through a CI/CD process the tests could pass and get merged but become flaky later on. This flakiness could come from a number of things like network issues, server load, database size, etc. Using the `--repeat` flag in your CD/CD process can help catch these flaky tests before they get merged to a main codebase. One strategy to use is run your tests like regular in your CI/CD process but if you're introducing a new test you can then run another set of tests with the new spec specified in `--spec` along with `--repeat` so it runs the new test x number of times. If the test fails any of those times then the test will not get merged and will need to be looked at why it failed. ``` # This will run the example.e2e.js spec 5 times npx wdio run ./wdio.conf.js --spec example.e2e.js --repeat 5 ``` --- Source: https://webdriver.io/docs/watcher.md # Watch Test Files With the WDIO testrunner you can watch files while you are working on them. They automatically rerun if you change either something in your app or in your test files. By adding a `--watch` flag when calling the `wdio` command the testrunner will wait for file changes after it ran all tests, e.g. ``` wdio wdio.conf.js --watch ``` By default it only watches for changes in your `specs` files. However by setting a `filesToWatch` property in your `wdio.conf.js` that contains a list of file paths (globbing supported) it will also watch for these files to be changed in order to rerun the whole suite. This is useful if you want to automatically rerun all your tests if you have changed your application code, e.g. ``` // wdio.conf.js export const config = { // ... filesToWatch: [ // watch for all JS files in my app './src/app/**/*.js' ], // ... } ``` info Try to run tests in parallel as much as possible. E2E tests are, by nature, slow. Rerunning tests is only useful if you can keep the individual test run time short. In order to save time, the testrunner keeps WebDriver sessions alive while waiting for file changes. Make sure your WebDriver backend can be modified so that it doesn't automatically close the session if no command was executed after some duration of time. --- Source: https://webdriver.io/docs/proxy.md # Proxy Setup You can tunnel two different types of request through a proxy: * connection between your test script and the browser driver (or WebDriver endpoint) * connection between the browser and the internet ## Proxy Between Driver And Test[​](#proxy-between-driver-and-test "Direct link to Proxy Between Driver And Test") If your company has a corporate proxy (e.g. on `http://my.corp.proxy.com:9090`) for all outgoing requests, you have two options to configure WebdriverIO to use the proxy: ### Option 1: Using Environment Variables (Recommended)[​](#option-1-using-environment-variables-recommended "Direct link to Option 1: Using Environment Variables (Recommended)") Starting from WebdriverIO v9.12.0, you can simply set the standard proxy environment variables: ``` export HTTP_PROXY=http://my.corp.proxy.com:9090 export HTTPS_PROXY=http://my.corp.proxy.com:9090 # Optional: bypass proxy for certain hosts export NO_PROXY=localhost,127.0.0.1,.internal.domain ``` Then run your tests as usual. WebdriverIO will automatically use these environment variables for proxy configuration. ### Option 2: Using undici's setGlobalDispatcher[​](#option-2-using-undicis-setglobaldispatcher "Direct link to Option 2: Using undici's setGlobalDispatcher") For more advanced proxy configurations or if you need programmatic control, you can use undici's `setGlobalDispatcher` method: #### Install undici[​](#install-undici "Direct link to Install undici") * npm * Yarn * pnpm * Bun ``` npm install undici --save-dev ``` ``` yarn add undici --dev ``` ``` pnpm add undici --save-dev ``` ``` bun add undici --dev ``` #### Add undici setGlobalDispatcher to your config file[​](#add-undici-setglobaldispatcher-to-your-config-file "Direct link to Add undici setGlobalDispatcher to your config file") Add the following require statement to the top of your config file. wdio.conf.js ``` import { setGlobalDispatcher, ProxyAgent } from 'undici'; const dispatcher = new ProxyAgent({ uri: new URL(process.env.https_proxy || 'http://my.corp.proxy.com:9090').toString() }); setGlobalDispatcher(dispatcher); export const config = { // ... } ``` Additional information about configuring the proxy can be located [here](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md). ### Which Method Should I Use?[​](#which-method-should-i-use "Direct link to Which Method Should I Use?") * **Use environment variables** if you want a simple, standard approach that works across different tools and doesn't require code changes. * **Use setGlobalDispatcher** if you need advanced proxy features like custom authentication, different proxy configurations per environment, or want to programmatically control proxy behavior. Both methods are fully supported and WebdriverIO will check for a global dispatcher first before falling back to environment variables. ### Sauce Connect Proxy[​](#sauce-connect-proxy "Direct link to Sauce Connect Proxy") If you use [Sauce Connect Proxy](https://docs.saucelabs.com/secure-connections/sauce-connect-5), start it via: ``` sc -u $SAUCE_USERNAME -k $SAUCE_ACCESS_KEY --no-autodetect -p http://my.corp.proxy.com:9090 ``` ## Proxy For Browser And Driver Downloads[​](#proxy-for-browser-and-driver-downloads "Direct link to Proxy For Browser And Driver Downloads") WebdriverIO downloads the browser and the driver it needs when they are not installed yet. * **Geckodriver and Edgedriver** downloads use `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY`. A dispatcher set with `setGlobalDispatcher` wins over these variables. * **Chrome, Chromium, Firefox and Chromedriver** downloads use `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` only when one of these is true: * the `proxy-agent` package is installed in your project: ``` npm install --save-dev proxy-agent ``` * Node.js runs with its built-in proxy support: ``` NODE_USE_ENV_PROXY=1 npx wdio run ./wdio.conf.ts ``` WebdriverIO does not install `proxy-agent` for you, because its dependency tree has security advisories without a fix. When a proxy variable is set and neither option is active, WebdriverIO logs a warning before the first download. ## Proxy Between Browser And Internet[​](#proxy-between-browser-and-internet "Direct link to Proxy Between Browser And Internet") In order to tunnel the connection between the browser and the internet, you can set up a proxy which can be useful to (for example) capture network information and other data with tools like [BrowserMob Proxy](https://github.com/lightbody/browsermob-proxy). The `proxy` parameters can be applied via the standard capabilities the following way: wdio.conf.js ``` export const config = { // ... capabilities: [{ browserName: 'chrome', // ... proxy: { proxyType: "manual", httpProxy: "corporate.proxy:8080", socksUsername: "codeceptjs", socksPassword: "secret", noProxy: "127.0.0.1,localhost" }, // ... }], // ... } ``` For more information, see the [WebDriver specification](https://w3c.github.io/webdriver/#proxy). --- Source: https://webdriver.io/docs/cloudservices.md # Using Cloud Services Using on-demand services like Sauce Labs, Browserstack, TestingBot, TestMu AI (Formerly LambdaTest) or Perfecto with WebdriverIO is pretty simple. All you need to do is to set your service's `user` and `key` in your options. Optionally, you can also parametrize your test by setting cloud-specific capabilities like `build`. If you only want to run cloud services in Travis, you can use the `CI` environment variable to check if you are in Travis and modify the config accordingly. ``` // wdio.conf.js export let config = {...} if (process.env.CI) { config.user = process.env.SAUCE_USERNAME config.key = process.env.SAUCE_ACCESS_KEY } ``` ## Sauce Labs[​](#sauce-labs "Direct link to Sauce Labs") You can set up your tests to run remotely in [Sauce Labs](https://saucelabs.com). The only requirement is to set the `user` and `key` in your config (either exported by `wdio.conf.js` or passed into `webdriverio.remote(...)`) to your Sauce Labs username and access key. You can also pass in any optional [test configuration option](https://docs.saucelabs.com/dev/test-configuration-options/) as a key/value in the capabilities for any browser. ### Sauce Connect[​](#sauce-connect "Direct link to Sauce Connect") If you want to run tests against a server that is not accessible to the Internet (like on `localhost`), then you need to use [Sauce Connect](https://docs.saucelabs.com/secure-connections/#sauce-connect-proxy). It is out of the scope of WebdriverIO to support this, so you'll have to start it by yourself. If you are using the WDIO testrunner download and configure the [`@wdio/sauce-service`](https://github.com/webdriverio/webdriverio/tree/main/packages/wdio-sauce-service) in your `wdio.conf.js`. It helps getting Sauce Connect running and comes with additional features that better integrate your tests into the Sauce service. ### With Travis CI[​](#with-travis-ci "Direct link to With Travis CI") Travis CI, however, does [have support](http://docs.travis-ci.com/user/sauce-connect/#Setting-up-Sauce-Connect) for starting Sauce Connect before each test, so following their directions for that is an option. If you do so, you must set the `tunnel-identifier` test configuration option in each browser's `capabilities`. Travis sets this to the `TRAVIS_JOB_NUMBER` environmental variable by default. Also, if you want to have Sauce Labs group your tests by build number, you can set the `build` to `TRAVIS_BUILD_NUMBER`. Lastly, if you set `name`, this changes the name of this test in Sauce Labs for this build. If you are using the WDIO testrunner combined with the [`@wdio/sauce-service`](https://github.com/webdriverio/webdriverio/tree/main/packages/wdio-sauce-service), WebdriverIO automatically sets a proper name for the test. Example `capabilities`: ``` browserName: 'chrome', version: '27.0', platform: 'XP', 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, name: 'integration', build: process.env.TRAVIS_BUILD_NUMBER ``` ### Timeouts[​](#timeouts "Direct link to Timeouts") Since you are running your tests remotely, it might be necessary to increase some timeouts. You can change the [idle timeout](https://docs.saucelabs.com/dev/test-configuration-options/#idletimeout) by passing `idle-timeout` as a test configuration option. This controls how long Sauce will wait between commands before closing the connection. ## BrowserStack[​](#browserstack "Direct link to BrowserStack") WebdriverIO also has a [Browserstack](https://www.browserstack.com) integration built-in. The only requirement is to set the `user` and `key` in your config (either exported by `wdio.conf.js` or passed into `webdriverio.remote(...)`) to your Browserstack automate username and access key. You can also pass in any optional [supported capabilities](https://www.browserstack.com/automate/capabilities) as a key/value in the capabilities for any browser. If you set `browserstack.debug` to `true` it will record a screencast of the session, which might be helpful. ### Local Testing[​](#local-testing "Direct link to Local Testing") If you want to run tests against a server that is not accessible to the Internet (like on `localhost`), then you need to use [Local Testing](https://www.browserstack.com/local-testing#command-line). It is out of the scope of WebdriverIO to support this, so you must start it by yourself. If you do use local, you should set `browserstack.local` to `true` in your capabilities. If you are using the WDIO testrunner, download and configure the [`@wdio/browserstack-service`](https://github.com/browserstack/wdio-browserstack-service) in your `wdio.conf.js`. It helps get BrowserStack running, and comes with additional features that better integrate your tests into the BrowserStack service. ### With Travis CI[​](#with-travis-ci-1 "Direct link to With Travis CI") If you want to add Local Testing in Travis, you have to start it by yourself. The following script will download and start it in the background. You should run this in Travis before starting the tests. ``` wget https://www.browserstack.com/browserstack-local/BrowserStackLocal-linux-x64.zip unzip BrowserStackLocal-linux-x64.zip ./BrowserStackLocal -v -onlyAutomate -forcelocal $BROWSERSTACK_ACCESS_KEY & sleep 3 ``` Also, you might wish set the `build` to the Travis build number. Example `capabilities`: ``` browserName: 'chrome', project: 'myApp', version: '44.0', build: `myApp #${process.env.TRAVIS_BUILD_NUMBER}.${process.env.TRAVIS_JOB_NUMBER}`, 'browserstack.local': 'true', 'browserstack.debug': 'true' ``` ## TestingBot[​](#testingbot "Direct link to TestingBot") The only requirement is to set the `user` and `key` in your config (either exported by `wdio.conf.js` or passed into `webdriverio.remote(...)`) to your [TestingBot](https://testingbot.com) username and secret key. You can also pass in any optional [supported capabilities](https://testingbot.com/support/other/test-options) as a key/value in the capabilities for any browser. ### Local Testing[​](#local-testing-1 "Direct link to Local Testing") If you want to run tests against a server that is not accessible to the Internet (like on `localhost`), then you need to use [Local Testing](https://testingbot.com/support/other/tunnel). TestingBot provides a Java-based tunnel to allow you to test websites not accessible from the internet. Their tunnel support page contains the information necessary to get this up and running. If you are using the WDIO testrunner, download and configure the [`@wdio/testingbot-service`](https://github.com/webdriverio/webdriverio/tree/main/packages/wdio-testingbot-service) in your `wdio.conf.js`. It helps get TestingBot running, and comes with additional features that better integrate your tests into the TestingBot service. ## TestMu AI (Formerly LambdaTest)[​](#testmu-ai-formerly-lambdatest "Direct link to TestMu AI (Formerly LambdaTest)") [TestMu AI](https://www.testmuai.com/) integration is also built-in. The only requirement is to set the `user` and `key` in your config (either exported by `wdio.conf.js` or passed into `webdriverio.remote(...)`) to your TestMu AI account username and access key. You can also pass in any optional [supported capabilities](https://www.testmuai.com/capabilities-generator/) as a key/value in the capabilities for any browser. If you set `visual` to `true` it will record a screencast of the session, which might be helpful. ### Tunnel for local testing[​](#tunnel-for-local-testing "Direct link to Tunnel for local testing") If you want to run tests against a server that is not accessible to the Internet (like on `localhost`), then you need to use [Local Testing](https://www.testmuai.com/support/docs/testing-locally-hosted-pages/). It is out of the scope of WebdriverIO to support this, so you must start it by yourself. If you do use local, you should set `tunnel` to `true` in your capabilities. If you are using the WDIO testrunner, download and configure the [`wdio-lambdatest-service`](https://github.com/LambdaTest/wdio-lambdatest-service) in your `wdio.conf.js`. It helps get TestMu AI running, and comes with additional features that better integrate your tests into the TestMu AI service. ### With Travis CI[​](#with-travis-ci-2 "Direct link to With Travis CI") If you want to add Local Testing in Travis, you have to start it by yourself. The following script will download and start it in the background. You should run this in Travis before starting the tests. ``` wget http://downloads.lambdatest.com/tunnel/linux/64bit/LT_Linux.zip unzip LT_Linux.zip ./LT -user $LT_USERNAME -key $LT_ACCESS_KEY -cui & sleep 3 ``` Also, you might wish set the `build` to the Travis build number. Example `capabilities`: ``` platform: 'Windows 10', browserName: 'chrome', version: '79.0', build: `myApp #${process.env.TRAVIS_BUILD_NUMBER}.${process.env.TRAVIS_JOB_NUMBER}`, 'tunnel': 'true', 'visual': 'true' ``` ## Perfecto[​](#perfecto "Direct link to Perfecto") When using wdio with [`Perfecto`](https://www.perfecto.io), you need to create a security token for each user and add this in the capabilities structure (in addition to other capabilities), as follows: ``` export const config = { capabilities: [{ // ... securityToken: "your security token" }], ``` In addition, you need to add cloud configuration, as follows: ``` hostname: "your_cloud_name.perfectomobile.com", path: "/nexperience/perfectomobile/wd/hub", port: 443, protocol: "https", ``` ## RobotActions[​](#robotactions "Direct link to RobotActions") [RobotActions](https://robotactions.com) provides real Android and iOS devices alongside browser nodes behind a single endpoint. It authenticates with an API token rather than a `user` and `key` pair. Send the token as a bearer header: ``` export const config = { protocol: 'https', hostname: 'grid.robotactions.com', port: 443, path: '/', headers: { Authorization: `Bearer ${process.env.RA_API_TOKEN}` }, capabilities: [{ browserName: 'chrome' }] } ``` Alternatively, pass the token as a path prefix, which the grid strips before forwarding the request: ``` export const config = { protocol: 'https', hostname: 'grid.robotactions.com', port: 443, path: `/t/${process.env.RA_API_TOKEN}/`, capabilities: [{ browserName: 'chrome' }] } ``` The grid additionally accepts credentials embedded in the URL (`https://user:token@host`) for other WebDriver clients, but that form cannot be used from WebdriverIO: it is fetch-based, and Node.js rejects URL-embedded credentials. To run against a real device, pass the browser as an Appium capability alongside either connection style above: ``` export const config = { protocol: 'https', hostname: 'grid.robotactions.com', port: 443, path: '/', headers: { Authorization: `Bearer ${process.env.RA_API_TOKEN}` }, capabilities: [{ platformName: 'Android', 'appium:browserName': 'chrome', 'appium:automationName': 'UiAutomator2' }] } ``` --- Source: https://webdriver.io/docs/seleniumgrid.md # Selenium Grid You can use WebdriverIO with your existing Selenium Grid instance. To connect your tests to Selenium Grid, you just need to update the options in your test runner configurations. Here is a code snippet from sample wdio.conf.ts. ``` export const config: WebdriverIO.Config = { // ... protocol: 'https', hostname: 'yourseleniumgridhost.yourdomain.com', port: 443, path: '/wd/hub', // ... } ``` You need to provide the appropriate values for the protocol, hostname, port, and path based on your Selenium Grid setup. If you are running Selenium Grid on the same machine as your test scripts, here are some typical options: ``` export const config: WebdriverIO.Config = { // ... protocol: 'http', hostname: 'localhost', port: 4444, path: '/wd/hub', // ... } ``` ### Basic authentication with protected Selenium Grid[​](#basic-authentication-with-protected-selenium-grid "Direct link to Basic authentication with protected Selenium Grid") It is highly recommended to secure your Selenium Grid. If you have a protected Selenium Grid that requires authentication, you can pass authentication headers via options. Please refer to the [headers](https://webdriver.io/docs/configuration/#headers) section in the documentation for more information. ### Timeout configurations with dynamic Selenium Grid[​](#timeout-configurations-with-dynamic-selenium-grid "Direct link to Timeout configurations with dynamic Selenium Grid") When using a dynamic Selenium Grid where browser pods are spun up on demand, session creation may face a cold start. In such cases, it is advised to increase the session creation timeouts. The default value in the options is 120 seconds, but you can increase it if your grid takes more time to create a new session. ``` connectionRetryTimeout: 180000, ``` ### Advanced configurations[​](#advanced-configurations "Direct link to Advanced configurations") For advanced configurations, please refer to the Testrunner [configuration file](https://webdriver.io/docs/configurationfile). ### File operations with Selenium Grid[​](#file-operations-with-selenium-grid "Direct link to File operations with Selenium Grid") When running test cases with a remote Selenium Grid, the browser runs on a remote machine, and you need to take special care with test cases involving file uploads and downloads. ### File downloads[​](#file-downloads "Direct link to File downloads") For Chromium-based browsers, you can refer to the [Download file](https://webdriver.io/docs/api/browser/downloadFile) documentation. If your test scripts need to read the content of a downloaded file, you need to download it from the remote Selenium node to the test runner machine. Here is an example code snippet from the sample `wdio.conf.ts` configuration for the Chrome browser: ``` export const config: WebdriverIO.Config = { // ... protocol: 'https', hostname: 'yourseleniumgridhost.yourdomain.com', port: 443, path: '/wd/hub', // ... capabilities: [{ browserName: 'chrome', 'se:downloadsEnabled': true }], //... } ``` ### File upload with remote Selenium Grid[​](#file-upload-with-remote-selenium-grid "Direct link to File upload with remote Selenium Grid") [`element.setFiles()`](/docs/api/element/setFiles.md) sets a file input through WebDriver BiDi. The paths you pass are opened by the browser, so they have to exist on the machine that runs the browser. WebdriverIO does not stage a local file onto a Selenium node. ``` await $('#file-upload').setFiles('/path/on/the/node/file.png') ``` A suite that used `browser.uploadFile()` to push bytes to the node has to put the file where the browser can read it, then call `setFiles`. The Selenium [`file`](/docs/api/selenium.md#file) endpoint is still available as `browser.file()` for Chromedriver, Edgedriver, and Selenium Grid. It is not a WebDriver or WebDriver BiDi command. ### Other file/grid operations[​](#other-filegrid-operations "Direct link to Other file/grid operations") There are a few more operations that you can perform with Selenium Grid. The instructions for Selenium Standalone should work fine with Selenium Grid as well. Please refer to the [Selenium Standalone](https://webdriver.io/docs/api/selenium/) documentation for available options. ### Selenium Grid Official documentation[​](#selenium-grid-official-documentation "Direct link to Selenium Grid Official documentation") For more information on Selenium Grid, you can refer to the official Selenium Grid [documentation](https://www.selenium.dev/documentation/grid/). If you wish to run Selenium Grid in Docker, Docker compose or Kubernetes, please refer to the Selenium-Docker [GitHub repository](https://github.com/SeleniumHQ/docker-selenium). --- Source: https://webdriver.io/docs/docker.md # Docker Docker is a powerful containerization technology that allows to encapsulate your test suite into a container that behaves the same on every system. This can avoid flakiness due to different browser or platform versions. In order to run your tests within a container, create a `Dockerfile` in your project directory, e.g.: ``` FROM selenium/standalone-chrome:134.0-20250323 # Change the browser and version according to your needs WORKDIR /app ADD . /app RUN npm install CMD npx wdio ``` Make sure you don't include your `node_modules` in your Docker image and have these installed when building the image. For that add a `.dockerignore` file with the following content: ``` node_modules ``` info We are using a Docker image here that comes with Selenium and Google Chrome pre-installed. There are various images available with different browser setups and browser versions. Check out the images maintained by the Selenium project [on Docker Hub](https://hub.docker.com/u/selenium). As we can only run Google Chrome in headless mode in our Docker container we have to modify our `wdio.conf.js` to ensure we do that: wdio.conf.js ``` export const config = { // ... capabilities: [{ maxInstances: 1, browserName: 'chrome', 'goog:chromeOptions': { args: [ '--no-sandbox', '--disable-infobars', '--headless', '--disable-gpu', '--window-size=1440,735' ], } }], // ... } ``` As mentioned in [Automation Protocols](/docs/automationProtocols.md) you can run WebdriverIO using the WebDriver protocol or WebDriver BiDi protocol. Make sure that the Chrome version installed on your image matches the [Chromedriver](https://www.npmjs.com/package/chromedriver) version you have defined in your `package.json`. To build the Docker container you can run: ``` docker build -t mytest -f Dockerfile . ``` Then to run the tests, execute: ``` docker run -it mytest ``` For more information on how to configure the Docker image, check out the [Docker docs](https://docs.docker.com/). ## Images where WebdriverIO downloads the browser[​](#images-where-webdriverio-downloads-the-browser "Direct link to Images where WebdriverIO downloads the browser") When the image has no browser, WebdriverIO downloads Chrome, Chromium, Firefox and Chromedriver itself. Chrome, Chromium and Chromedriver come as zip files, and WebdriverIO extracts them with the `unzip` command on Linux and macOS (`tar.exe` or PowerShell on Windows). Slim images, such as `node:24-slim`, and minimal Alpine images do not have `unzip`, so install it in your `Dockerfile`: ``` FROM node:24-slim RUN apt-get update && apt-get install -y --no-install-recommends unzip && rm -rf /var/lib/apt/lists/* ``` On Alpine, use `RUN apk add --no-cache unzip`. Without it, the download fails with `Extraction failed: no zip archiver is available`. --- Source: https://webdriver.io/docs/githubactions.md # Github Actions If your repository is hosted on Github, you can use [Github Actions](https://docs.github.com/en/actions) to run your tests on Github's infrastructure. 1. every time you push changes 2. on every pull request creation 3. on scheduled time 4. by manual trigger In the root of your repository, create a `.github/workflows` directory. Add a Yaml file, for example `.github/workflows/ci.yaml`. In there you will configure how to run your tests. See [jasmine-boilerplate](https://github.com/webdriverio/jasmine-boilerplate/blob/master/.github/workflows/ci.yaml) for reference implementation, and [sample test runs](https://github.com/webdriverio/jasmine-boilerplate/actions?query=workflow%3ACI). .github/workflows/ci.yaml ``` loading... ``` [View on GitHub]() Find out in the [Github Docs](https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow?tool=cli) on more information about creating workflow files. ## Firefox on Windows runners[​](#firefox-on-windows-runners "Direct link to Firefox on Windows runners") By default, Geckodriver creates each temporary Firefox profile in `%TEMP%`, on the `C:` system disk. On a GitHub-hosted Windows runner, several Firefox sessions that start at the same time fill the disk queue of `C:`. The running Firefox sessions then stop answering for 5 to 20 seconds, and tests time out. When WebdriverIO starts Geckodriver on Windows in GitHub Actions (`RUNNER_TEMP` is set), it creates the Firefox profiles in `RUNNER_TEMP`, which is on `D:` on GitHub-hosted runners. Geckodriver still deletes each profile when the session ends. A `profileRoot` that you set always wins. To keep the profiles in `%TEMP%`: wdio.conf.ts ``` import os from 'node:os' export const config: WebdriverIO.Config = { // ... capabilities: [{ browserName: 'firefox', 'wdio:geckodriverOptions': { profileRoot: os.tmpdir() } }] } ``` Measured on `windows-latest` (Windows Server 2025, 2 cores, 4 logical processors), with up to 4 Chrome and Firefox sessions at the same time, 10 jobs each: | Profiles in | Firefox stalls of 5 s or more | Session start (`POST /session`), median / max | | --------------------- | ----------------------------- | --------------------------------------------- | | `%TEMP%` on `C:` | 14, in 7 of 10 jobs | 7.3 s / 36.0 s | | `RUNNER_TEMP` on `D:` | 0 | 2.3 s / 13.0 s | Other CI systems do not set `RUNNER_TEMP`, so the profiles stay in `%TEMP%`. If you see the same stalls there, set `profileRoot` to a folder on a disk that is not the system disk: | CI system | Default in WebdriverIO | Temporary folder of the CI | | ----------------------------- | ------------------------------------------------------------------- | -------------------------- | | GitHub Actions, GitHub-hosted | profiles in `RUNNER_TEMP` (`D:`) | `RUNNER_TEMP` | | GitHub Actions, self-hosted | profiles in `RUNNER_TEMP` (check that it is not on the system disk) | `RUNNER_TEMP` | | Azure Pipelines | `%TEMP%` (not measured) | `AGENT_TEMPDIRECTORY` | | Jenkins | `%TEMP%` | `WORKSPACE_TMP` | | Other CI systems | `%TEMP%` | — | --- Source: https://webdriver.io/docs/jenkins.md # Jenkins WebdriverIO offers a tight integration to CI systems like [Jenkins](https://jenkins-ci.org). With the `junit` reporter, you can easily debug your tests as well as keep track of your test results. The integration is pretty easy. 1. Install the `junit` test reporter: `$ npm install @wdio/junit-reporter --save-dev`) 2. Update your config to save your XUnit results where Jenkins can find them, (and specify the `junit` reporter): ``` // wdio.conf.js module.exports = { // ... reporters: [ 'dot', ['junit', { outputDir: './' }] ], // ... } ``` It is up to you which framework to choose. The reports will be similar. For this tutorial, we’ll use Jasmine. After you have written couple of tests, you can setup a new Jenkins job. Give it a name and a description: ![Name And Description](/assets/images/jobname-841228a8d4d6197e9304fd229b159635.png "Name And Description") Then make sure it grabs always the newest version of your repository: ![Jenkins Git Setup](/assets/images/gitsetup-999b69ca31a59a7dd0febfd22aaac586.png "Jenkins Git Setup") **Now the important part:** Create a `build` step to execute shell commands. The `build` step needs to build your project. Since this demo project only tests an external app, you don't need to build anything. Just install the node dependencies and run the command `npm test` (which is an alias for `node_modules/.bin/wdio test/wdio.conf.js`). If you have installed a plugin like AnsiColor, but logs are still not colored, run tests with environment variable `FORCE_COLOR=1` (e.g., `FORCE_COLOR=1 npm test`). ![Build Step](/assets/images/runjob-84d85126ca08b9a47af4b76584121bb9.png "Build Step") After your test, you’ll want Jenkins to track your XUnit report. To do so, you have to add a post-build action called *"Publish JUnit test result report"*. You could also install an external XUnit plugin to track your reports. The JUnit one comes with the basic Jenkins installation and is sufficient enough for now. According to the config file, the XUnit reports will be saved in the project’s root directory. These reports are XML files. So, all you need to do in order to track the reports is to point Jenkins to all XML files in your root directory: ![Post-build Action](/assets/images/postjob-296a7236110427e02ef338aa1ce17166.png "Post-build Action") That's it! You’ve now set up Jenkins to run your WebdriverIO jobs. Your job will now provide detailed test results with history charts, stacktrace information on failed jobs, and a list of commands with payload that got used in each test. ![Jenkins Final Integration](/assets/images/final-ed1259540a822513a2dc527fd0f22162.png "Jenkins Final Integration") --- Source: https://webdriver.io/docs/bamboo.md # Bamboo WebdriverIO offers a tight integration to CI systems like [Bamboo](https://www.atlassian.com/software/bamboo). With the [JUnit](https://webdriver.io/docs/junit-reporter.html) or [Allure](https://webdriver.io/docs/allure-reporter.html) reporter, you can easily debug your tests as well as keep track of your test results. The integration is pretty easy. 1. Install the JUnit test reporter: `$ npm install @wdio/junit-reporter --save-dev`) 2. Update your config to save your JUnit results where Bamboo can find them, (and specify the `junit` reporter): ``` // wdio.conf.js module.exports = { // ... reporters: [ 'dot', ['junit', { outputDir: './testresults/' }] ], // ... } ``` Note: *It's always a good standard to keep the test results in separate folder than in the root folder.* ``` // wdio.conf.js - For tests running in parallel module.exports = { // ... reporters: [ 'dot', ['junit', { outputDir: './testresults/', outputFileFormat: function (options) { return `results-${options.cid}.xml`; } }] ], // ... } ``` The reports will be similar for all the frameworks and you can use anyone: Mocha, Jasmine or Cucumber. By this time, we believe you have the tests written up and results are generated in `./testresults/` folder, and your Bamboo is up and running. ## Integrate your tests in Bamboo[​](#integrate-your-tests-in-bamboo "Direct link to Integrate your tests in Bamboo") 1. Open your Bamboo project > Create a new plan, link your repository (make sure it always points to newest version of your repository) and create your stages ![Plan Details](/assets/images/plancreation-f213dbfbe41218276ff7a2ead54e8a9b.png "Plan Details") I will go with the default stage and job. In your case, you can create your own stages and jobs ![Default Stage](/assets/images/defaultstage-7ad0df0424adc095c99b087276d3d9fd.png "Default Stage") 2. Open your testing job and create tasks to run your tests in Bamboo > **Task 1:** Source Code Checkout > **Task 2:** Run your tests `npm i && npm run test`. You can use *Script* task and *Shell Interpreter* to run the above commands (This will generate the test results and save them in `./testresults/` folder) ![Test Run](/assets/images/testrun-2d411803d457ef5480e79df2965e7025.png "Test Run") > **Task: 3** Add *jUnit Parser* task to parse your saved test results. Please specify the test results directory here (you can use Ant style patterns as well) ![jUnit Parser](/assets/images/junitparser-1d4381f65fceb04a29217548956676a8.png "jUnit Parser") Note: *Make sure you are keeping the results parser task in *Final* section, so that it always get executed even if your test task is failed* > **Task: 4** (optional) In order to make sure that your test results are not messed up with old files, you can create a task to remove the `./testresults/` folder after a successful parse to Bamboo. You can add a shell script like `rm -f ./testresults/*.xml` to remove the results or `rm -r testresults` to remove the complete folder Once the above *rocket science* is done, please enable the plan and run it. Your final output will be like: ## Successful Test[​](#successful-test "Direct link to Successful Test") ![Successful Test](/assets/images/successfulltest-ae3af833690fc334ed539d5dd44e96c7.png "Successful Test") ## Failed Test[​](#failed-test "Direct link to Failed Test") ![Failed Test](/assets/images/failedtest-84ad31bb29d5316113cfa64d7cdf53e1.png "Failed Test") ## Failed and Fixed[​](#failed-and-fixed "Direct link to Failed and Fixed") ![Failed and Fixed](/assets/images/failedandfixed-38eaf428b669590f308918f0b7c66683.png "Failed and Fixed") Yay!! That's all. You have successfully integrated your WebdriverIO tests in Bamboo.