# WebdriverIO v10 documentation: Writing Tests
> 17 pages. Index of all sections: https://webdriver.io/llms.txt
---
Source: https://webdriver.io/docs/selectors.md
# Selectors
The [WebDriver Protocol](https://w3c.github.io/webdriver/) provides several selector strategies to query an element. WebdriverIO simplifies them to keep selecting elements simple. Please note that even though the command to query elements is called `$` and `$$`, they have nothing to do with jQuery or the [Sizzle Selector Engine](https://github.com/jquery/sizzle).
While there are so many different selectors available, only a few of them provide a resilient way to find the right element. For example, given the following button:
```
```
We **do** and **do not** recommend the following selectors:
| Selector | Recommended | Notes |
| ------------------------------------------ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `$('button')` | π¨ Never | Worst - too generic, no context. |
| `$('.btn.btn-large')` | π¨ Never | Bad. Coupled to styling. Highly subject to change. |
| `$('#main')` | β οΈ Sparingly | Better. But still coupled to styling or JS event listeners. |
| `$(() => document.queryElement('button'))` | β οΈ Sparingly | Effective querying, complex to write. |
| `$('button[name="submission"]')` | β οΈ Sparingly | Coupled to the `name` attribute which has HTML semantics. |
| `$('button[data-testid="submit"]')` | β Good | Requires additional attribute, not connected to a11y. |
| `$('aria/Submit')` | β Good | Good. Resembles how the user interacts with the page. It is recommended to use translation files so your tests don't break when translations are updated. On WebDriver BiDi sessions this uses the browser accessibility tree. On Classic sessions it falls back to XPath and can be slower on large pages. |
| `$('button=Submit')` | β Always | Best. Resembles how the user interacts with the page and is fast. It is recommended to use translation files so your tests don't break when translations are updated. |
## Strict Mode[β](#strict-mode "Direct link to Strict Mode")
As of v10 the [`$`](/docs/api/browser/$.md) command is **strict**: it represents exactly one element. If the selector matches more than one element, the command throws a `StrictSelectorError` instead of silently picking the first match:
```
// there are 12 buttons on the page
await $('button').click()
// StrictSelectorError: strict mode violation: `$("button")` resolved to 12 elements, expected 1.
```
This is the same behavior as [Playwright locators](https://playwright.dev/docs/locators#strictness). Cypress differs: its queries may resolve to several elements, and it is the action commands such as [`.click()`](https://docs.cypress.io/api/commands/click#Click-all-elements-with-id-starting-with-btn) that reject a multi-element subject by default. Strict mode surfaces selectors that are too broad, which would otherwise silently interact with the wrong element as soon as the page grows.
The rule applies to every step of a [chain](#chain-selectors) and to every selector type `$` accepts β string selectors (including ones that pierce the shadow DOM), [JS functions](#js-function), [mobile selectors](#mobile-selectors) and [custom strategy](#custom-selector-strategies) references.
### What is not affected[β](#what-is-not-affected "Direct link to What is not affected")
* `$$` keeps returning zero or many elements, as an [`ElementArray`](/docs/api/browser/$$.md). Await the list (or its `.length`) before you read the count or use `for...of`. `for await` works on the list directly.
* The dedicated helper commands `custom$`, `shadow$` and `react$` are not strict β they still return their first match, as do their `$$` counterparts.
* A selector that matches nothing still returns a lazily-resolved element, so [`waitForExist`](/docs/api/element/waitForExist.md) and the [auto-waiting](/docs/autowait.md) behavior are unchanged.
* Passing an element reference, e.g. `$(await browser.getActiveElement())`, always refers to a single node and is never checked.
Migrating to v10
For how to audit your suite for strict-mode violations, narrow or opt out of individual queries, and disable strict mode project-wide, see the [v10 migration guide](/docs/v10-migration.md).
## CSS Query Selector[β](#css-query-selector "Direct link to CSS Query Selector")
If not indicated otherwise, WebdriverIO will query elements using the [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors) pattern, e.g.:
selectors/example.js
```
loading...
```
[View on GitHub]()
## Link Text[β](#link-text "Direct link to Link Text")
To get an anchor element with a specific text in it, query the text starting with an equals (`=`) sign.
For example:
selectors/example.html
```
loading...
```
[View on GitHub]()
You can query this element by calling:
selectors/example.js
```
loading...
```
[View on GitHub]()
## Partial Link Text[β](#partial-link-text "Direct link to Partial Link Text")
To find a anchor element whose visible text partially matches your search value, query it by using `*=` in front of the query string (e.g. `*=driver`).
You can query the element from the example above by also calling:
selectors/example.js
```
loading...
```
[View on GitHub]()
**Note:** You can't mix multiple selector strategies in one selector. Use multiple chained element queries to reach the same goal, e.g.:
```
const elem = await $('header h1*=Welcome') // doesn't work!!!
// use instead
const elem = await $('header').$('*=driver')
```
## Element with certain text[β](#element-with-certain-text "Direct link to Element with certain text")
The same technique can be applied to elements as well. Additionally, it is also possible to do a case-insensitive matching using `.=` or `.*=` within the query.
For example, here's a query for a level 1 heading with the text "Welcome to my Page":
selectors/example.html
```
loading...
```
[View on GitHub]()
You can query this element by calling:
selectors/example.js
```
loading...
```
[View on GitHub]()
Or using query partial text:
selectors/example.js
```
loading...
```
[View on GitHub]()
The same works for `id` and `class` names:
selectors/example.html
```
loading...
```
[View on GitHub]()
You can query this element by calling:
selectors/example.js
```
loading...
```
[View on GitHub]()
**Note:** You can't mix multiple selector strategies in one selector. Use multiple chained element queries to reach the same goal, e.g.:
```
const elem = await $('header h1*=Welcome') // doesn't work!!!
// use instead
const elem = await $('header').$('h1*=Welcome')
```
## Tag Name[β](#tag-name "Direct link to Tag Name")
To query an element with a specific tag name, use `` or ``.
selectors/example.html
```
loading...
```
[View on GitHub]()
You can query this element by calling:
selectors/example.js
```
loading...
```
[View on GitHub]()
## Name Attribute[β](#name-attribute "Direct link to Name Attribute")
For querying elements with a specific name attribute, use a CSS selector such as `[name="some-name"]`. On a mobile session that same shorthand is sent with Appium's `name` locator strategy:
selectors/example.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
**Note:** The `name` locator strategy is an Appium locator. Desktop sessions keep `[name="some-name"]` on the CSS strategy.
## xPath[β](#xpath "Direct link to xPath")
It is also possible to query elements via a specific [xPath](https://developer.mozilla.org/en-US/docs/Web/XPath).
An xPath selector has a format like `//body/div[6]/div[1]/span[1]`.
selectors/xpath.html
```
loading...
```
[View on GitHub]()
You can query the second paragraph by calling:
selectors/example.js
```
loading...
```
[View on GitHub]()
You can use xPath to also traverse up and down the DOM tree:
selectors/example.js
```
loading...
```
[View on GitHub]()
## Accessibility Name Selector[β](#accessibility-name-selector "Direct link to Accessibility Name Selector")
Query elements by their accessible name. The accessible name is what is announced by a screen reader when that element receives focus. The value of the accessible name can be both visual content or hidden text alternatives.
On [WebDriver BiDi](https://w3c.github.io/webdriver-bidi/) sessions (Chrome, Edge, Firefox and other BiDi-capable browsers) WebdriverIO first uses [`browsingContext.locateNodes`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes) with an accessibility locator. That queries the browser accessibility tree directly and is typically much faster than the XPath approximation. If the accessibility locator finds nothing, WebdriverIO falls back to the Classic XPath heuristic so existing `aria/` queries keep matching.
info
You can read more about this selector in our [release blog post](/blog/2022/09/05/accessibility-selector)
### Fetch by `aria-label`[β](#fetch-by-aria-label "Direct link to fetch-by-aria-label")
selectors/aria.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
### Fetch by `aria-labelledby`[β](#fetch-by-aria-labelledby "Direct link to fetch-by-aria-labelledby")
selectors/aria.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
### Fetch by content[β](#fetch-by-content "Direct link to Fetch by content")
selectors/aria.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
### Fetch by title[β](#fetch-by-title "Direct link to Fetch by title")
selectors/aria.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
### Fetch by `alt` property[β](#fetch-by-alt-property "Direct link to fetch-by-alt-property")
selectors/aria.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
## Role Selector[β](#role-selector "Direct link to Role Selector")
Query elements by their ARIA role and accessible name, the way a screen reader describes them: "the *Add to cart* button". A role plus a name keeps matching when class names, test ids or the DOM structure change.
```
await $('role/button[name="Add to cart"]').click()
await expect($('role/heading[name="Order summary"]')).toBeDisplayed()
// role only
const rows = await $$('role/row')
// scoped to a parent element
const dialog = $('role/dialog[name="Checkout"]')
await dialog.$('role/button[name="Pay now"]').click()
```
The syntax is `role/` or `role/[name=""]`. Single quotes work too, and a quote inside the name is escaped with a backslash: `role/button[name="Say \"hi\""]`.
* The name has to match the full accessible name.
* The role has to be an ARIA role. A typo fails with the closest valid role, for example `"buton" is not an ARIA role. Did you mean "button"?`.
* `img` and its ARIA 1.3 name `image` are the same role.
* The selector follows the [strict mode](#strict-mode) of `$` like every other selector.
On a [WebDriver BiDi](https://w3c.github.io/webdriver-bidi/) session, WebdriverIO passes role and name to [`browsingContext.locateNodes`](https://w3c.github.io/webdriver-bidi/#command-browsingContext-locateNodes). The browser computes both itself, the same way assistive technology sees the page. Elements inside open shadow roots and inside frames, including frames from another origin, are found. If the browser finds no element, there is no fallback to a heuristic. Note that the browser decides the role: for example, a `
` without headers or caption can be a layout table, and its rows then have no `row` role.
On a WebDriver Classic session, and when a browser does not support the role locator, WebdriverIO computes role and accessible name in the page with [`dom-accessibility-api`](https://github.com/eps1lon/dom-accessibility-api), the implementation Testing Library uses. A text field without a label is named by its `placeholder`, as browsers do. The role selector is not available in a native mobile app context. Use an [accessibility id](#accessibility-id) there.
## ARIA - Role Attribute[β](#aria---role-attribute "Direct link to ARIA - Role Attribute")
For querying elements based on [ARIA roles](https://www.w3.org/TR/html-aria/#docconformance), you can directly specify role of the element like `[role=button]` as selector parameter. This selector approximates the role from the element name and attributes. Prefer the [role selector](#role-selector), which uses the role the browser computes and can also match the accessible name:
selectors/aria.html
```
loading...
```
[View on GitHub]()
selectors/example.js
```
loading...
```
[View on GitHub]()
## ID Attribute[β](#id-attribute "Direct link to ID Attribute")
Locator strategy "id" is not supported in WebDriver protocol, one should use either CSS or xPath selector strategies instead to find elements using ID.
However some drivers (e.g. [Appium You.i Engine Driver](https://github.com/YOU-i-Labs/appium-youiengine-driver#selector-strategies)) might still [support](https://github.com/YOU-i-Labs/appium-youiengine-driver#selector-strategies) this selector.
Current supported selector syntaxes for ID are:
```
//css locator
const button = await $('#someid')
//xpath locator
const button = await $('//*[@id="someid"]')
//id strategy
// Note: works only in Appium or similar frameworks which supports locator strategy "ID"
const button = await $('id=resource-id/iosname')
```
## JS Function[β](#js-function "Direct link to JS Function")
You can also use JavaScript functions to fetch elements using web native APIs. Of course, you can only do this inside a web context (e.g., `browser`, or web context in mobile).
Given the following HTML structure:
selectors/js.html
```
loading...
```
[View on GitHub]()
You can query the sibling element of `#elem` as follows:
selectors/example.js
```
loading...
```
[View on GitHub]()
## Deep Selectors[β](#deep-selectors "Direct link to Deep Selectors")
warning
Starting with `v9` of WebdriverIO there is no need for this special selector as WebdriverIO automatically pierces through the Shadow DOM for you. It is recommended to migrate off this selector by removing the `>>>` in front it.
On a WebDriver BiDi session, `$` and `$$` look into every open shadow root: roots created with `attachShadow()` and declarative shadow roots (``) that the page or `setHTMLUnsafe()` adds to the document. They do not look into a closed declarative shadow root, or into a declarative shadow root that `setHTMLUnsafe()` creates in an element that is not in the document yet. For these, use [`shadow$`](https://webdriver.io/docs/api/element/shadow$) on the host element.
Many frontend applications heavily rely on elements with [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM). It is technically impossible to query elements within the shadow DOM without workarounds. The [`shadow$`](https://webdriver.io/docs/api/element/shadow$) and [`shadow$$`](https://webdriver.io/docs/api/element/shadow$$) have been such workarounds that had their [limitations](https://github.com/Georgegriff/query-selector-shadow-dom#how-is-this-different-to-shadow). With the deep selector you can now query all elements within any shadow DOM using the common query command.
Given we have an application with the following structure:

With this selector you can query the `` element that is nested within another shadow DOM, e.g.:
selectors/example.js
```
loading...
```
[View on GitHub]()
## Mobile Selectors[β](#mobile-selectors "Direct link to Mobile Selectors")
For hybrid mobile testing, it's important that the automation server is in the correct *context* before executing commands. For automating gestures, the driver ideally should be set to native context. But to select elements from the DOM, the driver will need to be set to the platform's webview context. Only *then* can the methods mentioned above can be used.
For native mobile testing, there is no switching between contexts, as you have to use mobile strategies and use the underlying device automation technology directly. This is especially useful when a test needs some fine-grained control over finding elements.
### Android UiAutomator[β](#android-uiautomator "Direct link to Android UiAutomator")
Androidβs UI Automator framework provides a number of ways to find elements. You can use the [UI Automator API](https://developer.android.com/tools/testing-support-library/index.html#uia-apis), in particular the [UiSelector class](https://developer.android.com/reference/androidx/test/uiautomator/UiSelector) to locate elements. In Appium you send the Java code, as a string, to the server, which executes it in the applicationβs environment, returning the element or elements.
```
const selector = 'new UiSelector().text("Cancel").className("android.widget.Button")'
const button = await $(`android=${selector}`)
await button.click()
```
### Android DataMatcher and ViewMatcher (Espresso only)[β](#android-datamatcher-and-viewmatcher-espresso-only "Direct link to Android DataMatcher and ViewMatcher (Espresso only)")
Android's DataMatcher strategy provides a way to find elements by [Data Matcher](https://developer.android.com/reference/android/support/test/espresso/DataInteraction)
```
const menuItem = await $({
"name": "hasEntry",
"args": ["title", "ViewTitle"]
})
await menuItem.click()
```
And similarly [View Matcher](https://developer.android.com/reference/android/support/test/espresso/ViewInteraction)
```
const menuItem = await $({
"name": "hasEntry",
"args": ["title", "ViewTitle"],
"class": "androidx.test.espresso.matcher.ViewMatchers"
})
await menuItem.click()
```
### Android View Tag (Espresso only)[β](#android-view-tag-espresso-only "Direct link to Android View Tag (Espresso only)")
The view tag strategy provides a convenient way to find elements by their [tag](https://developer.android.com/reference/android/support/test/espresso/matcher/ViewMatchers.html#withTagValue%28org.hamcrest.Matcher%3Cjava.lang.Object%3E%29).
```
const elem = await $('-android viewtag:tag_identifier')
await elem.click()
```
### iOS UIAutomation[β](#ios-uiautomation "Direct link to iOS UIAutomation")
When automating an iOS application, Appleβs [UI Automation framework](https://developer.apple.com/library/prerelease/tvos/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/UIAutomation.html) can be used to find elements.
This JavaScript [API](https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/index.html#//apple_ref/doc/uid/TP40009771) has methods to access to the view and everything on it.
```
const selector = 'UIATarget.localTarget().frontMostApp().mainWindow().buttons()[0]'
const button = await $(`ios=${selector}`)
await button.click()
```
You can also use predicate searching within iOS UI Automation in Appium to refine element selection even further. See [here](https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/ios/ios-predicate.md) for details.
### iOS XCUITest predicate strings and class chains[β](#ios-xcuitest-predicate-strings-and-class-chains "Direct link to iOS XCUITest predicate strings and class chains")
With iOS 10 and above (using the `XCUITest` driver), you can use [predicate strings](https://github.com/facebook/WebDriverAgent/wiki/Predicate-Queries-Construction-Rules):
```
const selector = `type == 'XCUIElementTypeSwitch' && name CONTAINS 'Allow'`
const switch = await $(`-ios predicate string:${selector}`)
await switch.click()
```
And [class chains](https://github.com/facebook/WebDriverAgent/wiki/Class-Chain-Queries-Construction-Rules):
```
const selector = '**/XCUIElementTypeCell[`name BEGINSWITH "D"`]/**/XCUIElementTypeButton'
const button = await $(`-ios class chain:${selector}`)
await button.click()
```
### Accessibility ID[β](#accessibility-id "Direct link to Accessibility ID")
The `accessibility id` locator strategy is designed to read a unique identifier for a UI element. This has the benefit of not changing during localization or any other process that might change text. In addition, it can be an aid in creating cross-platform tests, if elements that are functionally the same have the same accessibility id.
* For iOS this is the `accessibility identifier` laid out by Apple [here](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIAccessibilityIdentification_Protocol/index.html).
* For Android the `accessibility id` maps to the `content-description` for the element, as described [here](https://developer.android.com/training/accessibility/accessible-app.html).
For both platforms, getting an element (or multiple elements) by their `accessibility id` is usually the best method. It is also the preferred way over the deprecated `name` strategy.
```
const elem = await $('~my_accessibility_identifier')
await elem.click()
```
### Class Name[β](#class-name "Direct link to Class Name")
The `class name` strategy is a `string` representing a UI element on the current view.
* For iOS it is the full name of a [UIAutomation class](https://developer.apple.com/library/prerelease/tvos/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/UIAutomation.html), and will begin with `UIA-`, such as `UIATextField` for a text field. A full reference can be found [here](https://developer.apple.com/library/ios/navigation/#section=Frameworks\&topic=UIAutomation).
* For Android it is the fully qualified name of a [UI Automator](https://developer.android.com/tools/testing-support-library/index.html#UIAutomator) [class](https://developer.android.com/reference/android/widget/package-summary.html), such `android.widget.EditText` for a text field. A full reference can be found [here](https://developer.android.com/reference/android/widget/package-summary.html).
* For Youi.tv it is the full name of a Youi.tv class, and will being with `CYI-`, such as `CYIPushButtonView` for a push button element. A full reference can be found at [You.i Engine Driver's GitHub page](https://github.com/YOU-i-Labs/appium-youiengine-driver)
```
// iOS example
await $('UIATextField').click()
// Android example
await $('android.widget.DatePicker').click()
// Youi.tv example
await $('CYIPushButtonView').click()
```
## Chain Selectors[β](#chain-selectors "Direct link to Chain Selectors")
If you want to be more specific in your query, you can chain selectors until you've found the right element. If you call `element` before your actual command, WebdriverIO starts the query from that element.
For example, if you have a DOM structure like:
```
```
And you want to add product B to the cart, it would be difficult to do that just by using the CSS selector.
With selector chaining, it's way easier. Simply narrow down the desired element step by step:
```
await $('.row .entry:nth-child(2)').$('button*=Add').click()
```
### Appium Image Selector[β](#appium-image-selector "Direct link to Appium Image Selector")
Using the `-image` locator strategy, it is possible to send an Appium an image file representing an element you want to access.
Supported file formats `jpg,png,gif,bmp,svg`
Full reference can be found [here](https://github.com/appium/appium/blob/master/packages/images-plugin/docs/find-by-image.md)
```
const elem = await $('./file/path/of/image/test.jpg')
await elem.click()
```
**Note**: The way how Appium works with this selector is that it will internally make a (app)screenshot and use the provided image selector to verify if the element can be found in that (app)screenshot.
Be aware of the fact that Appium might resize the taken (app)screenshot to make it match the CSS-size of your (app)screen (this will happen on iPhones but also on Mac machines with a Retina display because the DPR is bigger than 1). This will result in not finding a match because the provided image selector might have been taken from the original screenshot. You can fix this by updating the Appium Server settings, see the [Appium docs](https://github.com/appium/appium/blob/master/packages/images-plugin/docs/find-by-image.md#related-settings) for the settings and [this comment](https://github.com/webdriverio/webdriverio/issues/6097#issuecomment-726675579) on a detailed explanation.
## React Selectors[β](#react-selectors "Direct link to React Selectors")
WebdriverIO provides a way to select React components based on the component name. To do this, you have a choice of two commands: `react$` and `react$$`.
These commands allow you to select components off the [React VirtualDOM](https://reactjs.org/docs/faq-internals.html) and return either a single WebdriverIO Element or an array of elements (depending on which function is used).
**Note**: The commands `react$` and `react$$` are similar in functionality, except that `react$$` will return *all* matching instances as an array of WebdriverIO elements, and `react$` will return the first found instance.
The commands work with React 16 to 19, for an app that starts with `createRoot` or with `ReactDOM.render`. They read the components of the current render, so they also find components that a state change added. If React has not rendered a root of the page yet, they wait up to 5 seconds for it.
#### Basic example[β](#basic-example "Direct link to Basic example")
```
// index.jsx
import React from 'react'
import { createRoot } from 'react-dom/client'
function MyComponent() {
return (
MyComponent
)
}
function App() {
return ()
}
createRoot(document.querySelector('#root')).render()
```
In the above code there is a simple `MyComponent` instance inside the application, which React is rendering inside a HTML element with `id="root"`.
With the `browser.react$` command, you can select an instance of `MyComponent`:
```
const myCmp = await browser.react$('MyComponent')
```
Now that you have the WebdriverIO element stored in `myCmp` variable, you can execute element commands against it.
#### Filtering components[β](#filtering-components "Direct link to Filtering components")
You can filter your selection by the props and/or the state of the component. To do so, pass `props` and/or `state` in the second argument of the command.
```
// index.jsx
import React from 'react'
import ReactDOM from 'react-dom'
function MyComponent(props) {
return (
Hello { props.name || 'World' }!
)
}
function App() {
return (
)
}
ReactDOM.render(, document.querySelector('#root'))
```
If you want to select the instance of `MyComponent` that has a prop `name` as `WebdriverIO`, you can execute the command like so:
```
const myCmp = await browser.react$('MyComponent', {
props: { name: 'WebdriverIO' }
})
```
If you wanted to filter our selection by state, the `browser` command would looks something like so:
```
const myCmp = await browser.react$('MyComponent', {
state: { myState: 'some value' }
})
```
A filter matches when each of its keys that the component also has matches. A key that the component does not have is ignored. A nested object matches the same way, and an array matches when it has one value in common with the array of the component. `null`, `false` and `0` match the same value. For a function component with hooks, the state is the state of the first hook (`useState` or `useReducer`): if the first hook is another hook, for example `useRef`, the state filter does not match. With both `props` and `state`, a component must match both.
#### Selector rules[β](#selector-rules "Direct link to Selector rules")
* `*` matches one or more characters: `browser.react$$('My*')` finds `MyComponent` and `MyOtherComponent`.
* Names separated by spaces find a component inside another one: `browser.react$$('List Item')` finds each `Item` inside a `List`.
* The name of a component is its `displayName`, or else the name of its function or class. A component of `React.memo` has the name of its function (the development build of React 17 also gives it the `displayName` of the memo object). A component of `React.forwardRef` has no name, unless it has a `displayName`.
* For a higher-order component with a name like `withRouter(MyComponent)`, the name inside the parentheses is used: `MyComponent`.
* Without an element scope, the commands search all React roots of the page, in the order of the document, also roots inside other roots and roots in open shadow roots. `react$` gives the first match. To search one root only, call the command on its container or on an element of that root: `$('#other-root').react$$('MyComponent')`.
* The results come root after root. In a root, they come in the order of the component tree, level by level, not in the order of the document. `react$$` gives each DOM node once.
* For an app in a frame, call the command on the browsing context of the frame, or on an element of the frame: `(await page.frame({ selector: 'iframe' })).react$$('MyComponent')`.
Known limits:
* A component that renders only text gives a text node. With WebDriver Classic, a text node cannot be sent back, and the command fails with `javascript error: circular reference`.
* While React hydrates a `Suspense` boundary of a server-rendered page, the components inside it do not exist yet. Wait until the page has finished to hydrate.
#### Dealing with `React.Fragment`[β](#dealing-with-reactfragment "Direct link to dealing-with-reactfragment")
When using the `react$` command to select React [fragments](https://reactjs.org/docs/fragments.html), WebdriverIO will return the first child of that component as the component's node. If you use `react$$`, you will receive an array containing all the HTML nodes inside the fragments that match the selector.
```
// index.jsx
import React from 'react'
import ReactDOM from 'react-dom'
function MyComponent() {
return (
MyComponent
MyComponent
)
}
function App() {
return ()
}
ReactDOM.render(, document.querySelector('#root'))
```
Given the above example, this is how the commands would work:
```
await browser.react$('MyComponent') // returns the WebdriverIO Element for the first
await browser.react$$('MyComponent') // returns the WebdriverIO Elements for the array [, ]
```
**Note:** If you have multiple instances of `MyComponent` and you use `react$$` to select these fragment components, you will be returned an one-dimensional array of all the nodes. In other words, if you have 3 `` instances, you will be returned an array with six WebdriverIO elements.
## Custom Selector Strategies[β](#custom-selector-strategies "Direct link to Custom Selector Strategies")
If your app requires a specific way to fetch elements you can define yourself a custom selector strategy that you can use with `custom$` and `custom$$`. For that register your strategy once in the beginning of the test, e.g. in a `before` hook:
queryElements/customStrategy.js
```
loading...
```
[View on GitHub]()
Given the following HTML snippet:
queryElements/example.html
```
loading...
```
[View on GitHub]()
Then use it by calling:
queryElements/customStrategy.js
```
loading...
```
[View on GitHub]()
**Note:** this only works in an web environment in which the [`execute`](/docs/api/browser/execute.md) command can be run.
---
Source: https://webdriver.io/docs/autowait.md
# Auto-waiting
When using a command that directly interacts with an element WebdriverIO will automatically wait for the element to be visible and interactable, no manual waits are needed when using the commands (think of click, setValue etc). An element is considered interactable when the conditions for [isClickable](https://webdriver.io/docs/api/element/isClickable) are met.
While WebdriverIO automatically waits for elements to become interactable, there are rare cases for which you might need to manually wait. For these rare cases we offer commands such as [`waitForDisplayed`](/docs/api/element/waitForDisplayed.md).
## Implicit timeouts (not recommended)[β](#implicit-timeouts-not-recommended "Direct link to Implicit timeouts (not recommended)")
While we do not recommend using this but the WebDriver protocol offers [implicit timeouts](https://w3c.github.io/webdriver/#timeouts) that allow specify how long the driver is suppose to wait for an element to show up. By default this timeout is set to `0` and therefore makes the driver return with an `no such element` error immediately if an element could not be found on the page. Increasing this timeout using the [`setTimeout`](/docs/api/browser/setTimeout.md) would make the driver wait and increases the chances that the element shows up eventually.
note
Read more about WebDriver and framework related timeouts in the [timeouts guide](/docs/timeouts.md)
---
Source: https://webdriver.io/docs/timeouts.md
# Timeouts
Each command in WebdriverIO is an asynchronous operation. A request is fired to the Selenium server (or a cloud service like [Sauce Labs](https://saucelabs.com)), and its response contains the result once the action has completed or failed.
Therefore, time is a crucial component in the whole testing process. When a certain action depends on the state of a different action, you need to make sure that they get executed in the right order. Timeouts play an important role when dealing with these issues.
## WebDriver Timeouts[β](#webdriver-timeouts "Direct link to WebDriver Timeouts")
### Session Script Timeout[β](#session-script-timeout "Direct link to Session Script Timeout")
A session has an associated session script timeout that specifies a time to wait for asynchronous scripts to run. Unless stated otherwise, it is 30 seconds. You can set this timeout like so:
```
await browser.setTimeout({ 'script': 60000 })
await browser.execute(async () => {
console.log('this should not fail')
await new Promise((resolve) => setTimeout(resolve, 59000))
})
```
### Session Page Load Timeout[β](#session-page-load-timeout "Direct link to Session Page Load Timeout")
A session has an associated session page load timeout that specifies a time to wait for the page loading to complete. Unless stated otherwise, it is 300,000 milliseconds.
You can set this timeout like so:
```
await browser.setTimeout({ 'pageLoad': 10000 })
```
> `pageLoad` is the WebDriver [timeouts](https://www.w3.org/TR/webdriver/#set-timeouts) name. WebdriverIO v10 accepts that key only.
### Session Implicit Wait Timeout[β](#session-implicit-wait-timeout "Direct link to Session Implicit Wait Timeout")
A session has an associated session implicit wait timeout. This specifies the time to wait for the implicit element location strategy when locating elements using the [`findElement`](/docs/api/webdriver.md#findelement) or [`findElements`](/docs/api/webdriver.md#findelements) commands ([`$`](/docs/api/browser/$.md) or [`$$`](/docs/api/browser/$$.md), respectively, when running WebdriverIO with or without the WDIO testrunner). Unless stated otherwise, it is 0 milliseconds.
You can set this timeout via:
```
await browser.setTimeout({ 'implicit': 5000 })
```
## WebdriverIO related timeouts[β](#webdriverio-related-timeouts "Direct link to WebdriverIO related timeouts")
### `WaitFor*` timeout[β](#waitfor-timeout "Direct link to waitfor-timeout")
WebdriverIO provides multiple commands to wait on elements to reach a certain state (e.g. enabled, visible, existing). These commands take a selector argument and a timeout number, which determines how long the instance should wait for that element to reach the state. The `waitforTimeout` option allows you to set the global timeout for all `waitFor*` commands, so you don't need to set the same timeout over and over again. *(Note the lowercase `f`!)*
```
// wdio.conf.js
export const config = {
// ...
waitforTimeout: 5000,
// ...
}
```
In your tests, you now can do this:
```
const myElem = await $('#myElem')
await myElem.waitForDisplayed()
// you can also overwrite the default timeout if needed
await myElem.waitForDisplayed({ timeout: 10000 })
```
### An element that the page removed[β](#an-element-that-the-page-removed "Direct link to An element that the page removed")
When the page removes or renders again an element, WebdriverIO finds it again with its selector and waits up to `waitforTimeout`. If it is there, the command runs on it. If not, the command fails with:
* `message`: `Can't call on element with selector "" because element wasn't found` (a `$$()` item: `β¦ "" at index β¦`; a removed parent: the message is about the parent)
* `cause`: the stale element reference error of the driver
`waitUntil` and `waitForEnabled` fail with their own error, which has this error as `cause`. `isDisplayed` and `isExisting` of the removed element do not wait: they give `false`. For a child of a removed parent, they wait and fail with this error.
test/specs/removed.e2e.ts
```
import { $, browser, expect } from '@wdio/globals'
describe('a removed element', () => {
it('gives the error of an element that was not found again', async () => {
await browser.url('https://webdriver.io')
const title = await $('h1')
await browser.execute(() => document.querySelectorAll('h1').forEach((h1) => h1.remove()))
const error = await title.getText().then(() => null, (err: Error) => err)
expect(error?.message).toContain('because element wasn\'t found')
})
})
```
## Framework related timeouts[β](#framework-related-timeouts "Direct link to Framework related timeouts")
The testing framework youβre using with WebdriverIO has to deal with timeouts, especially since everything is asynchronous. It ensures that the test process doesn't get stuck if something goes wrong.
By default, the timeout is 10 seconds, which means that a single test should not take longer than that.
A single test in Mocha looks like:
```
it('should login into the application', async () => {
await browser.url('/login')
const form = await $('form')
const username = await $('#username')
const password = await $('#password')
await username.setValue('userXY')
await password.setValue('******')
await form.submit()
expect(await browser.getTitle()).to.be.equal('Admin Area')
})
```
In Cucumber, the timeout applies to a single step definition. However, if you want to increase the timeout because your test takes longer than the default value, you need to set it in the framework options.
* Mocha
* Jasmine
* Cucumber
```
// wdio.conf.js
export const config = {
// ...
framework: 'mocha',
mochaOpts: {
timeout: 20000
},
// ...
}
```
```
// wdio.conf.js
export const config = {
// ...
framework: 'jasmine',
jasmineOpts: {
defaultTimeoutInterval: 20000
},
// ...
}
```
```
// wdio.conf.js
export const config = {
// ...
framework: 'cucumber',
cucumberOpts: {
timeout: 20000
},
// ...
}
```
### Mocha timeouts and the WebdriverIO hooks[β](#mocha-timeouts-and-the-webdriverio-hooks "Direct link to Mocha timeouts and the WebdriverIO hooks")
A Mocha test or hook can change its own timeout with `this.timeout(ms)`. Use a `function`, not an arrow function, to get `this`. WebdriverIO follows the change, also `this.timeout(0)`, which turns the timeout off. With `mochaOpts.parallelMode`, only `mochaOpts.timeout` applies: `this.timeout()` in a test or hook throws, and a timeout of a suite or of `it(...).timeout()` is ignored, with a warning. See [Parallel Tests in a Spec File](/docs/parallel-tests.md#hooks-and-timeouts).
The timeout of a test includes the time of its `beforeTest` hook, as Mocha starts the timer before the hook. With the [retry option](/docs/retry.md#rerun-single-tests-in-jasmine-or-mocha) of WebdriverIO, all attempts of a test share one timeout.
When a test or hook times out, WebdriverIO runs `afterTest` (or `afterHook`) before Mocha starts the next test, so that hook cannot run at the same time as the next test. Mocha waits for these hooks up to one more timeout of the test.
---
Source: https://webdriver.io/docs/assertion.md
# Assertion
The [WDIO testrunner](https://webdriver.io/docs/clioptions) comes with a built in assertion library that allows you to make powerful assertions on various aspects of the browser or elements within your (web) application. It extends [Jests Matchers](https://jestjs.io/docs/en/using-matchers) functionality with additional, for e2e testing optimized, matchers, e.g.:
```
const $button = await $('button')
await expect($button).toBeDisplayed()
```
or
```
const selectOptions = await $$('form select>option')
// make sure there is at least one option in select
await expect(selectOptions).toHaveChildren({ gte: 1 })
```
For the full list, see the [expect API doc](/docs/api/expect-webdriverio.md).
Jasmine
With the Jasmine framework, `expect` combines Jasmine's matchers and the WebdriverIO matchers. Jasmine's sync matchers do not need `await`, and the Jest parts of `expect`, such as `expect.soft()`, are not available. See [Using Jasmine](/docs/frameworks.md#assertions).
## Soft Assertions[β](#soft-assertions "Direct link to Soft Assertions")
WebdriverIO includes soft assertions by default from `expect-webdriverio` (since 5.2.0). Soft assertions allow your tests to continue execution even when an assertion fails. All failures are collected and reported at the end of the test.
### Usage[β](#usage "Direct link to Usage")
```
// These won't throw immediately if they fail
await expect.soft(await $('h1').getText()).toEqual('Basketball Shoes');
await expect.soft(await $('#price').getText()).toMatch(/β¬\d+/);
// Regular assertions still throw immediately
await expect(await $('.add-to-cart').isClickable()).toBe(true);
```
## Migrating from Chai[β](#migrating-from-chai "Direct link to Migrating from Chai")
[Chai](https://www.chaijs.com/) and [expect-webdriverio](https://github.com/webdriverio/expect-webdriverio#readme) can coexist, and with some minor adjustments a smooth transition to expect-webdriverio can be achieved. If you've upgraded to WebdriverIO v6 then by default you will have access to all the assertions from `expect-webdriverio` out of the box. This means that globally wherever you use `expect` you would call an `expect-webdriverio` assertion. That is, unless you you set [`injectGlobals`](/docs/configuration.md#injectglobals) to `false` or have explicitly overridden the global `expect` to use Chai. In this case you would not have access to any of the expect-webdriverio assertions without explicitly importing the expect-webdriverio package where you need it.
This guide will show examples of how to migrate from Chai if it has been overridden locally and how to migrate from Chai if it has been overridden globally.
### Local[β](#local "Direct link to Local")
Assume Chai was imported explicitly in a file, e.g.:
```
// myfile.js - original code
import { expect as expectChai } from 'chai'
describe('Homepage', () => {
it('should assert', async () => {
await browser.url('./')
expectChai(await browser.getUrl()).to.include('/login')
})
})
```
To migrate this code remove the Chai import and use the new expect-webdriverio assertion method `toHaveUrl` instead:
```
// myfile.js - migrated code
describe('Homepage', () => {
it('should assert', async () => {
await browser.url('./')
await expect(browser).toHaveUrl('/login') // new expect-webdriverio API method https://webdriver.io/docs/api/expect-webdriverio.html#tohaveurl
});
});
```
If you wanted to use both Chai and expect-webdriverio in the same file you would keep the Chai import and `expect` would default to the expect-webdriverio assertion, e.g.:
```
// myfile.js
import { expect as expectChai } from 'chai'
import { expect as expectWDIO } from '@wdio/globals'
describe('Element', () => {
it('should be displayed', async () => {
const isDisplayed = await $("#element").isDisplayed()
expectChai(isDisplayed).to.equal(true); // Chai assertion
})
});
describe('Other element', () => {
it('should not be displayed', async () => {
await expectWDIO($("#element")).not.toBeDisplayed(); // expect-webdriverio assertion
})
})
```
### Global[β](#global "Direct link to Global")
Assume `expect` was globally overridden to use Chai. In order to use expect-webdriverio assertions we need to globally set a variable in the "before" hook, e.g.:
```
// wdio.conf.js
before: async () => {
await import('expect-webdriverio');
global.wdioExpect = global.expect;
const chai = await import('chai');
global.expect = chai.expect;
}
```
Now Chai and expect-webdriverio can be used alongside each other. In your code you would use Chai and expect-webdriverio assertions as follows, e.g.:
```
// myfile.js
describe('Element', () => {
it('should be displayed', async () => {
const isDisplayed = await $("#element").isDisplayed()
expect(isDisplayed).to.equal(true); // Chai assertion
});
});
describe('Other element', () => {
it('should not be displayed', async () => {
await expectWdio($("#element")).not.toBeDisplayed(); // expect-webdriverio assertion
});
});
```
To migrate you would slowly move each Chai assertion over to expect-webdriverio. Once all Chai assertions have been replaced throughout the code base the "before" hook can be deleted. A global find and replace to replace all instances of `wdioExpect` to `expect` will then finish off the migration.
---
Source: https://webdriver.io/docs/pageobjects.md
# Page Object Pattern
Version 5 of WebdriverIO was designed with Page Object Pattern support in mind. By introducing the "elements as first class citizens" principle, it is now possible to build up large test suites using this pattern.
There are no additional packages required to create page objects. It turns out that clean, modern classes provide all necessary features we need:
* inheritance between page objects
* lazy loading of elements
* encapsulation of methods and actions
The goal of using page objects is to abstract any page information away from the actual tests. Ideally, you should store all selectors or specific instructions that are unique for a certain page in a page object, so that you still can run your test after you've completely redesigned your page.
## Making A Page Object[β](#making-a-page-object "Direct link to Making A Page Object")
First off, we need a main page object that we call `Page.js`. It will contain general selectors or methods which all page objects will inherit from.
```
// Page.js
export default class Page {
constructor() {
this.title = 'My Page'
}
async open (path) {
await browser.url(path)
}
}
```
We will always `export` an instance of a page object, and never create that instance in the test. Since we are writing end-to-end tests, we always consider the page as a stateless constructβjust as each HTTP request is a stateless construct.
Sure, the browser can carry session information and therefore can display different pages based on different sessions, but this shouldn't be reflected within a page object. These sorts of state changes should live in your actual tests.
Let's start testing the first page. For demo purposes, we use [The Internet](http://the-internet.herokuapp.com) website by [Elemental Selenium](http://elementalselenium.com) as guinea pig. Let's try to build a page object example for the [login page](http://the-internet.herokuapp.com/login).
## `Get` -ing Your Selectors[β](#get--ing-your-selectors "Direct link to get--ing-your-selectors")
The first step is to write all important selectors that are required in our `login.page` object as getter functions:
```
// login.page.js
import Page from './page'
class LoginPage extends Page {
get username () { return $('#username') }
get password () { return $('#password') }
get submitBtn () { return $('form button[type="submit"]') }
get flash () { return $('#flash') }
get headerLinks () { return $$('#header a') }
async open () {
await super.open('login')
}
async submit () {
await this.submitBtn.click()
}
}
export default new LoginPage()
```
Defining selectors in getter functions might look a little weird, but itβs really useful. These functions are evaluated *when you access the property*, not when you generate the object. With that you always request the element before you do an action on it.
## Chaining Commands[β](#chaining-commands "Direct link to Chaining Commands")
WebdriverIO internally remembers the last result of a command. If you chain an element command with an action command, it finds the element from the previous command and uses the result to execute the action. With that you can remove the selector (first parameter) and the command looks as simple as:
```
await LoginPage.username.setValue('Max Mustermann')
```
Which is basically the same thing as:
```
let elem = await $('#username')
await elem.setValue('Max Mustermann')
```
or
```
await $('#username').setValue('Max Mustermann')
```
## Using Page Objects In Your Tests[β](#using-page-objects-in-your-tests "Direct link to Using Page Objects In Your Tests")
After you've defined the necessary elements and methods for the page, you can start to write the test for it. All you need to do to use the page object is to `import` (or `require`) it. That's it!
Since you exported an already-created instance of the page object, importing it lets you start using it right away.
If you use an assertion framework, your tests can be even more expressive:
```
// login.spec.js
import LoginPage from '../pageobjects/login.page'
describe('login form', () => {
it('should deny access with wrong creds', async () => {
await LoginPage.open()
await LoginPage.username.setValue('foo')
await LoginPage.password.setValue('bar')
await LoginPage.submit()
await expect(LoginPage.flash).toHaveText('Your username is invalid!')
})
it('should allow access with correct creds', async () => {
await LoginPage.open()
await LoginPage.username.setValue('tomsmith')
await LoginPage.password.setValue('SuperSecretPassword!')
await LoginPage.submit()
await expect(LoginPage.flash).toHaveText('You logged into a secure area!')
})
})
```
From the structural side, it makes sense to separate spec files and page objects into different directories. Additionally you can give each page object the ending: `.page.js`. This makes it more clear that you import a page object.
## Page Objects As Fixtures[β](#page-objects-as-fixtures "Direct link to Page Objects As Fixtures")
With the [Vitest framework](/docs/frameworks.md#using-vitest) you can hand page objects to your tests as [Vitest fixtures](https://vitest.dev/guide/test-context.html#test-extend) instead of importing a shared instance. Each test then gets a fresh page object, declares in its signature which pages it needs, and can rely on setup and teardown (open the page, log in, log out) that the fixture runs around it. Mocha, Jasmine and Cucumber have no fixtures, so keep using exported instances there.
Export the class next to the instance, so a fixture can create its own object:
test/pageobjects/page.ts
```
export default class Page {
async open (path: string) {
await browser.url(path)
}
}
```
test/pageobjects/login.page.ts
```
import Page from './page.js'
export class LoginPage extends Page {
get username () { return $('#username') }
get password () { return $('#password') }
get submitBtn () { return $('form button[type="submit"]') }
get flash () { return $('#flash') }
async open () {
await super.open('/login')
}
async login (username: string, password: string) {
await this.username.setValue(username)
await this.password.setValue(password)
await this.submitBtn.click()
}
}
export default new LoginPage()
```
test/pageobjects/secure.page.ts
```
import Page from './page.js'
export class SecurePage extends Page {
get flash () { return $('#flash') }
get logoutBtn () { return $('a[href="/logout"]') }
async logout () {
await this.logoutBtn.click()
}
}
export default new SecurePage()
```
Define the fixtures once with `test.extend`. Code before `use()` is setup, code after it is teardown, and a fixture can depend on another fixture by destructuring it:
test/fixtures.ts
```
import { test as base } from 'vitest'
import { LoginPage } from './pageobjects/login.page.js'
import { SecurePage } from './pageobjects/secure.page.js'
type PageFixtures = {
loginPage: LoginPage
securePage: SecurePage
}
export const test = base.extend({
// Vitest requires the first argument to be destructured, even when no fixture is used
// eslint-disable-next-line no-empty-pattern
loginPage: async ({}, use) => {
const loginPage = new LoginPage()
await loginPage.open()
await use(loginPage)
},
securePage: async ({ loginPage }, use) => {
await loginPage.login('tomsmith', 'SuperSecretPassword!')
const securePage = new SecurePage()
await use(securePage)
await securePage.logout()
}
})
```
Import that `test` in your specs and ask for the page objects by name. A fixture only runs for the tests that use it, so `securePage` (and the login it needs) is skipped in the first test:
test/specs/login.spec.ts
```
import { describe } from 'vitest'
import { test } from '../fixtures.js'
describe('login form', () => {
test('should deny access with wrong creds', async ({ loginPage }) => {
await loginPage.login('foo', 'bar')
await expect(loginPage.flash).toHaveText('Your username is invalid!', { containing: true })
})
test('should allow access with correct creds', async ({ securePage }) => {
await expect(securePage.flash).toHaveText('You logged into a secure area!', { containing: true })
})
})
```
`expect` is the global WebdriverIO assertion library. Don't import it from `vitest` (see [Using Vitest](/docs/frameworks.md#using-vitest)).
Fixtures also work with `test.concurrent`. Fixture setup and teardown run inside the test, so their commands target the test's own window. Use `parallelMode: 'userContexts'` for fixtures that log in, because with `'contexts'` all concurrent tests share cookies, and one test's logout would end the others' sessions:
test/specs/secure.spec.ts
```
import { describe } from 'vitest'
import { test } from '../fixtures.js'
describe('secure area', () => {
test.concurrent('shows the welcome message', async ({ securePage }) => {
await expect(securePage.flash).toHaveText('You logged into a secure area!', { containing: true })
})
test.concurrent('shows the logout button', async ({ securePage }) => {
await expect(securePage.logoutBtn).toBeDisplayed()
})
})
```
## Going Further[β](#going-further "Direct link to Going Further")
This is the basic principle of how to write page objects with WebdriverIO. But you can build up way more complex page object structures than this! For example, you might have specific page objects for modals, or split up a huge page object into different classes (each representing a different part of the overall web page) that inherit from the main page object. The pattern really provides a lot of opportunities to separate page information from your tests, which is important to keep your test suite structured and clear in times where the project and number of tests grows.
You can find this example (and even more page object examples) in the [`example` folder](https://github.com/webdriverio/webdriverio/tree/main/examples/pageobject) on GitHub.
---
Source: https://webdriver.io/docs/mocksandspies.md
# Request Mocks and Spies
WebdriverIO comes with built-in support for modifying network responses that allows you to focus testing your frontend application without having to setup your backend or a mock server. You can define custom responses for web resources like REST API requests in your test and modify them dynamically.
info
Note that using the `mock` command requires support for WebDriver Bidi. That is usually the case when running tests locally in a Chromium based browser or on Firefox as well as if you use a Selenium Grid v4 or higher. If you run tests in the cloud, make sure that your cloud provider supports WebDriver Bidi.
## Creating a mock[β](#creating-a-mock "Direct link to Creating a mock")
Before you can modify any responses you have define a mock first. This mock is described by the resource url and can be filtered by the [request method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) or [headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers). The resource is matched using a [`URLPattern`](https://developer.mozilla.org/en-US/docs/Web/API/URLPattern), where `*` matches any sequence of characters. A url without a protocol is matched against the path of the request only, so `*/users/list` matches that path on any origin:
```
// mock all resources ending with "/users/list"
const userListMock = await browser.mock('*/users/list')
// or you can specify the mock by filtering resources by headers or
// status code, only mock successful requests to json resources
const strictMock = await browser.mock('*', {
// mock all json responses
requestHeaders: { 'Content-Type': 'application/json' },
// that were successful
statusCode: 200
})
// instead of a string you can also pass in a `URLPattern`; the polyfill
// also works in runtimes without native URLPattern support
import { URLPattern } from 'urlpattern-polyfill'
const patternMock = await browser.mock(new URLPattern({ pathname: '/users/list' }))
```
info
A single `*` matches any characters, `/` included. In a string pattern, WebdriverIO changes `**` to `*`, so `'**/api/**'` is the same as `'*/api/*'`.
A second mock with the same URL pattern and the same filter options replaces the first one: WebdriverIO restores the first mock, so it no longer changes requests or records calls. To keep both mocks, give them different filter options. For example, the strings `'**/users'` and `'*/users'` are the same mock, while `'*/users'` and `'*/users'` with `{ method: 'POST' }` are two mocks.
warning
WebdriverIO does not change a `URLPattern` object. In an object, use a single `*`: repeated wildcards before fixed text, such as `{ pathname: '**/api/**' }`, can make the match very slow on a long URL that does not match, and freeze a test. See [issue #13548](https://github.com/webdriverio/webdriverio/issues/13548).
In component tests, use a fixed protocol and hostname to keep runner traffic outside the intercept; see [component testing request mocks](/docs/component-testing/mocking.md#requests).
## Specifying custom responses[β](#specifying-custom-responses "Direct link to Specifying custom responses")
Once you have defined a mock you can define custom responses for it. Those custom responses can be either an object to respond a JSON, a local file to respond with a custom fixture or a web resource to replace the response with a resource from the internet.
### Mocking API Requests[β](#mocking-api-requests "Direct link to Mocking API Requests")
In order to mock API requests where you expect a JSON response all you need to do is to call `respond` on the mock object with an arbitrary object you want to return, e.g.:
```
const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/')
mock.respond([{
title: 'Injected (non) completed Todo',
order: null,
completed: false
}, {
title: 'Injected completed Todo',
order: null,
completed: true
}], {
headers: {
'Access-Control-Allow-Origin': '*'
},
fetchResponse: false
})
await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/')
await $('#todo-list li').waitForExist()
console.log(await $$('#todo-list li').map(el => el.getText()))
// outputs: "[ 'Injected (non) completed Todo', 'Injected completed Todo' ]"
```
You can also modify the response headers as well as the status code by passing in some mock response params as follows:
```
mock.respond({ ... }, {
// respond with status code 404
statusCode: 404,
// merge response headers with following headers
headers: { 'x-custom-header': 'foobar' }
})
```
If you want the mock not to call the backend at all, you can pass `false` for the `fetchResponse` flag.
```
mock.respond({ ... }, {
// do not call the actual backend
fetchResponse: false
})
```
`fetchResponse: false` never calls the backend. A mock created with a `statusCode` or `responseHeaders` filter needs that response to decide whether it matches, so `respond()` and `respondOnce()` throw if you combine them. Drop the response filter, or leave `fetchResponse` unset so the mock can read the backend response and then replace it.
It is recommend to store custom responses in fixture files so you can just require them in your test as follows:
```
import responseFixture from './__fixtures__/apiResponse.json' with { type: 'json' }
mock.respond(responseFixture)
```
### Mocking text resources[β](#mocking-text-resources "Direct link to Mocking text resources")
If you like to modify text resources like JavaScript, CSS files or other text based resources you can just pass in a file path and WebdriverIO will replaces the original resource with it, e.g.:
```
const scriptMock = await browser.mock('*/script.min.js')
scriptMock.respond('./tests/fixtures/script.js')
// or respond with your custom JS
scriptMock.respond('alert("I am a mocked resource")')
```
### Redirect web resources[β](#redirect-web-resources "Direct link to Redirect web resources")
You can also just replace a web resource with another web resource if your desired response is already hosted on the web. This works with individual page resources as well as with a webpage itself, e.g.:
```
const pageMock = await browser.mock('https://google.com/')
await pageMock.respond('https://webdriver.io')
await browser.url('https://google.com')
console.log(await browser.getTitle()) // returns "WebdriverIO Β· Next-gen browser and mobile automation test framework for Node.js"
```
### Dynamic responses[β](#dynamic-responses "Direct link to Dynamic responses")
If your mock response depends on the original resource response you can also dynamically modify the resource by passing in a function receives the original response as parameter and sets the mock based on the return value, e.g.:
```
const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/', {
method: 'get'
})
mock.respond((req) => {
// replace todo content with their list number
return req.body.map((item, i) => ({ ...item, title: i }))
})
await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/')
await $('#todo-list li').waitForExist()
console.log(await $$('#todo-list li label').map((el) => el.getText()))
// returns
// [
// '0', '1', '2', '19', '20',
// '21', '3', '4', '5', '6',
// '7', '8', '9', '10', '11',
// '12', '13', '14', '15', '16',
// '17', '18', '22'
// ]
```
## Aborting mocks[β](#aborting-mocks "Direct link to Aborting mocks")
Instead of returning a custom response you can also just abort the request with one of the following HTTP errors:
* Failed
* Aborted
* TimedOut
* AccessDenied
* ConnectionClosed
* ConnectionReset
* ConnectionRefused
* ConnectionAborted
* ConnectionFailed
* NameNotResolved
* InternetDisconnected
* AddressUnreachable
* BlockedByClient
* BlockedByResponse
This is very useful if you want to block 3rd party script from your page that have a negative influence on your functional test. You can abort a mock by just calling `abort` or `abortOnce`, e.g.:
```
const mock = await browser.mock('https://www.google-analytics.com/*')
mock.abort('Failed')
```
## Spies[β](#spies "Direct link to Spies")
Every mock is automatically a spy that counts the amount of requests the browser made to that resource. If you don't apply a custom response or abort reason to the mock it continues with the default response you would normally receive. This allows you to check how many times the browser made the request, e.g. to a certain API endpoint.
```
const mock = await browser.mock('*/user', { method: 'post' })
console.log(mock.calls.length) // returns 0
// register user
await $('#username').setValue('randomUser')
await $('password').setValue('password123')
await $('password_repeat').setValue('password123')
await $('button[type="submit"]').click()
// check if API request was made
expect(mock.calls.length).toBe(1)
// assert response
expect(mock.calls[0].body).toEqual({ success: true })
```
If you need to wait until a matching request has responded, use `mock.waitForResponse(options)`. See the API reference: [waitForResponse](/docs/api/mock/waitForResponse.md).
## Multi-remote[β](#multi-remote "Direct link to Multi-remote")
On a [multi-remote](/docs/multiremote.md) browser, `mock()` returns a `MultiRemoteMock` rather than one `Mock`. Methods such as `respond()` and `restore()` run on every instance. `waitForResponse()` waits until every instance has a matching response. Captured requests stay on the mock for that browser:
```
const mock = await browser.mock('*/user', { method: 'post' })
mock.respond({ success: true })
// register a user in every browser so each session sends the request
await browser.$('#username').setValue('randomUser')
await browser.$('#password').setValue('password123')
await browser.$('#password_repeat').setValue('password123')
await browser.$('button[type="submit"]').click()
await mock.waitForResponse()
expect(mock.getInstance('myChromeBrowser').calls).toHaveLength(1)
expect(mock.getInstance('myFirefoxBrowser').calls).toHaveLength(1)
```
`mock.instances` lists those names in the order the mocks were created. `getInstance` throws `Multi-remote object has no instance named ""` when the name is not in that list. A mock created from `browser.select('myFirefoxBrowser', 'myChromeBrowser')` lists Firefox first, which can differ from `browser.instances`.
To stub one browser only, call `mock()` on that instance:
```
const chromeOnly = await browser.getInstance('myChromeBrowser').mock('*/user')
```
---
Source: https://webdriver.io/docs/emulation.md
# Emulation
With WebdriverIO you can emulate browser behavior using the [`emulate`](/docs/api/browser/emulate.md) command. The command drives the [WebDriver BiDi emulation module](https://w3c.github.io/webdriver-bidi/#module-emulation) for the current top-level browsing context. The override applies immediately. You do not reload the page. `clock` is the exception: BiDi has no clock command, so that scope still installs fake timers.
info
This feature requires WebDriver Bidi support for the browser. While recent versions of Chrome, Edge and Firefox have such support, Safari **does not**. For updates follow [wpt.fyi](https://wpt.fyi/results/webdriver/tests/bidi/emulation?label=experimental\&label=master\&aligned). Furthermore if you use a cloud vendor for spawning browsers, make sure your vendor also supports WebDriver Bidi.
To enable WebDriver Bidi for your test, make sure to have `webSocketUrl: true` set in your capabilities.
A browser that does not implement a command rejects the call with its own error, `unknown command` or `unsupported operation`. WebdriverIO returns that error. It does not fall back to a preload script or to CDP.
`emulate` returns a function that clears that scope. [`browser.restore()`](/docs/api/browser/restore.md) clears every active scope, or the scopes you list.
## Geolocation[β](#geolocation "Direct link to Geolocation")
Change the browser geolocation to a specific area, e.g.:
```
await browser.emulate('geolocation', {
latitude: 52.52,
longitude: 13.39,
accuracy: 100
})
await browser.setPermissions({ name: 'geolocation' }, 'granted')
await browser.url('https://www.google.com/maps')
await browser.$('aria/Show Your Location').click()
await browser.pause(5000)
console.log(await browser.getUrl()) // outputs: "https://www.google.com/maps/@52.52,13.39,16z?entry=ttu"
```
This uses the browser geolocation stack, including `getCurrentPosition` and `watchPosition`. A page can still need the geolocation permission granted, as in the example. Optional fields are `accuracy`, `altitude`, `altitudeAccuracy`, `heading` and `speed`.
To make the page fail to read a position:
```
await browser.emulate('geolocation', { error: 'positionUnavailable' })
```
## Color Scheme and other media features[β](#color-scheme-and-other-media-features "Direct link to Color Scheme and other media features")
Change the `prefers-color-scheme` media feature:
```
await browser.emulate('colorScheme', 'light')
await browser.url('https://webdriver.io')
const backgroundColor = await browser.$('nav').getCSSProperty('background-color')
console.log(backgroundColor.parsed.hex) // outputs: "#efefef"
await browser.emulate('colorScheme', 'dark')
const backgroundColorDark = await browser.$('nav').getCSSProperty('background-color')
console.log(backgroundColorDark.parsed.hex) // outputs: "#000000"
```
This updates CSS `@media (prefers-color-scheme)` as well as [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia). No reload is required.
`media` sets the rest of the media-feature map, for example reduced motion:
```
await browser.emulate('media', { prefersReducedMotion: 'reduce', hover: 'none' })
```
`colorScheme` and `media` share one map. The BiDi command replaces the whole map, so the later call wins. Restoring either scope clears the map.
`forcedColors` is a different command. It sets the forced-colors theme (`'light'` or `'dark'`), not the `forced-colors` media feature. That media feature stays on `media` as `forcedColors: 'none' | 'active'`.
## User Agent[β](#user-agent "Direct link to User Agent")
Change the user agent of the browser via:
```
await browser.emulate('userAgent', 'Chrome/1.2.3.4 Safari/537.36')
```
This is the browser's user-agent override. It is not a patched `navigator.userAgent` property. Browser vendors are progressively deprecating the User Agent.
## Online state[β](#online-state "Direct link to Online state")
Take the browsing context offline:
```
await browser.emulate('onLine', false)
```
`false` sends `emulation.setNetworkConditions` with `{ type: 'offline' }`. Fetch, WebSocket and WebTransport fail, and [`navigator.onLine`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) follows. `true`, and restoring the scope, clears the condition. Throughput and latency stay on [`throttleNetwork`](/docs/api/browser/throttleNetwork.md). BiDi network conditions only support offline.
## Locale, timezone and touch[β](#locale-timezone-and-touch "Direct link to Locale, timezone and touch")
```
await browser.emulate('locale', 'fr-FR')
await browser.emulate('timezone', 'Pacific/Honolulu')
await browser.emulate('touch', 1)
```
`locale` is a BCP 47 tag. `timezone` is an IANA name or an offset such as `+02:00`. `touch` is `maxTouchPoints` and must be an integer `>= 1`. Restoring `touch` clears the override. It cannot set `0`.
## Screen, orientation and layout[β](#screen-orientation-and-layout "Direct link to Screen, orientation and layout")
```
await browser.emulate('screen', { width: 390, height: 844 })
await browser.emulate('orientation', { natural: 'portrait', type: 'portrait-primary' })
await browser.emulate('viewportMeta', true)
await browser.emulate('textLayout', 'mobile')
await browser.emulate('scrollbar', 'overlay')
await browser.emulate('scripting', false)
```
`screen` is the web-exposed screen area, not the viewport. `orientation.natural` is `'portrait'` or `'landscape'`. `orientation.type` is `'portrait-primary'`, `'portrait-secondary'`, `'landscape-primary'` or `'landscape-secondary'`.
`viewportMeta` only accepts `true`. The spec value is `true | null`, so there is no `false`. Restore clears it. `textLayout` only accepts `'mobile'`. `scripting` can only be disabled. The spec cannot force scripting on. `scrollbar` is `'classic'` or `'overlay'`.
## Clock[β](#clock "Direct link to Clock")
You can modify the browser system clock using the [`emulate`](/docs/emulation.md) command. It overrides native global functions related to time allowing them to be controlled synchronously via `clock.tick()` or the yielded clock object. This includes controlling:
* `setTimeout`
* `clearTimeout`
* `setInterval`
* `clearInterval`
* `Date Objects`
The clock starts at the unix epoch (timestamp of 0). This means that when you instantiate new Date in your application, it will have a time of January 1st, 1970 if you don't pass any other options to the `emulate` command.
##### Example[β](#example "Direct link to Example")
When calling `browser.emulate('clock', { ... })` it will immediately overwrite the global functions for the current page as well as all following pages, e.g.:
```
const clock = await browser.emulate('clock', { now: new Date(1989, 7, 4) })
console.log(await browser.execute(() => (new Date()).toString()))
// returns "Fri Aug 04 1989 00:00:00 GMT-0700 (Pacific Daylight Time)"
await browser.url('https://webdriverio')
console.log(await browser.execute(() => (new Date()).toString()))
// returns "Fri Aug 04 1989 00:00:00 GMT-0700 (Pacific Daylight Time)"
await clock.restore()
console.log(await browser.execute(() => (new Date()).toString()))
// returns "Thu Aug 01 2024 17:59:59 GMT-0700 (Pacific Daylight Time)"
await browser.url('https://guinea-pig.webdriver.io/pointer.html')
console.log(await browser.execute(() => (new Date()).toString()))
// returns "Thu Aug 01 2024 17:59:59 GMT-0700 (Pacific Daylight Time)"
```
You can modify the system time by calling [`setSystemTime`](/docs/api/clock/setSystemTime.md) or [`tick`](/docs/api/clock/tick.md).
The `FakeTimerInstallOpts` object can have the following properties:
```
interface FakeTimerInstallOpts {
// Installs fake timers with the specified unix epoch
// @default: 0
now?: number | Date | undefined;
// An array with names of global methods and APIs to fake. By default, WebdriverIO
// does not replace `nextTick()` and `queueMicrotask()`. For instance,
// `browser.emulate('clock', { toFake: ['setTimeout', 'nextTick'] })` will fake only
// `setTimeout()` and `nextTick()`
toFake?: FakeMethod[] | undefined;
// The maximum number of timers that will be run when calling runAll() (default: 1000)
loopLimit?: number | undefined;
// Tells WebdriverIO to increment mocked time automatically based on the real system
// time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change
// in the real system time)
// @default false
shouldAdvanceTime?: boolean | undefined;
// Relevant only when using with shouldAdvanceTime: true. increment mocked time by
// advanceTimeDelta ms every advanceTimeDelta ms change in the real system time
// @default: 20
advanceTimeDelta?: number | undefined;
// Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their
// respective handlers. These are not cleared by default, leading to potentially
// unexpected behavior if timers existed prior to installing FakeTimers.
// @default: false
shouldClearNativeTimers?: boolean | undefined;
}
```
## Device[β](#device "Direct link to Device")
The `emulate` command also supports emulating a certain mobile or desktop device. This should, by no means, be used for mobile testing as desktop browser engines differ from mobile ones. This should only be used if your application offers a specific behavior for smaller viewport sizes.
For a device, WebdriverIO:
* sets the user agent from the descriptor
* sets the viewport and device scale factor
* sets `maxTouchPoints` to `1` when the descriptor has touch, and clears touch otherwise
* sets mobile text layout and the viewport meta tag when the descriptor is mobile, and clears them otherwise
It does not invent a screen size or an orientation from the device name. Viewport is not `screen.width`. Use the `screen` and `orientation` scopes for those.
The viewport change is sent to the top-level context that was current when `emulate` was called. Restoring the device resizes that context, including after a switch to another window.
If the browser rejects one of those commands, the previous user agent, viewport, touch, text layout and viewport meta are put back and the error is returned. A custom user agent or `setViewport` size is not replaced with a default.
```
const restore = await browser.emulate('device', 'iPhone 15')
// test your application ...
// reset user agent, viewport, touch, text layout and viewport meta
await restore()
```
WebdriverIO maintains a fixed list of [all defined devices](https://github.com/webdriverio/webdriverio/blob/main/packages/webdriverio/src/deviceDescriptorsSource.ts).
---
Source: https://webdriver.io/docs/snapshot.md
# Snapshot
Snapshot tests can be very useful for asserting a wide range of aspects of your component or logic at the same time. In WebdriverIO you can take snapshots of any arbitrary object as well as a WebElement DOM structure or WebdriverIO command results.
Similar to other test frameworks WebdriverIO will take a snapshot of the given value, then compare it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the result.
Cross Platform Support
These snapshot capabilities are available for running end-to-end tests within the Node.js environment as well as for running [unit and component](/docs/component-testing.md) tests in the browser or on mobile devices.
## Use Snapshots[β](#use-snapshots "Direct link to Use Snapshots")
To snapshot a value, you can use the `toMatchSnapshot()` from [`expect()`](/docs/api/expect-webdriverio.md) API:
```
import { browser, expect } from '@wdio/globals'
it('can take a DOM snapshot', () => {
await browser.url('https://guinea-pig.webdriver.io/')
await expect($('.findme')).toMatchSnapshot()
})
```
The first time this test is run, WebdriverIO creates a snapshot file that looks like this:
```
// Snapshot v1
exports[`main suite 1 > can take a DOM snapshot 1`] = `"