Селектори
The WebDriver Protocol 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.
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:
<button
id="main"
class="btn btn-large"
name="submission"
role="button"
data-testid="submit"
>
Submit
</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. Note: This selector can be slower than others 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. |
CSS Query Selector
If not indicated otherwise, WebdriverIO will query elements using the CSS selector pattern, e.g.:
selectors/example.js
loading...