Writing custom selectors with crusher
What you'll learn?
- Different ways to write selectors
Often, when writing complex test flows or to ensure stability across tests, you'll have to write custom selectors for your test. This guide will go through different ways to write selectors and their advantages.
Writing Selectors
Depending on your web app and your needs, there are different approaches you can choose when writing selectors.
- Text Selectors
- CSS Selectors
- XPath Selectors
🦖 Pros:
- No need to go through the DOM tree to write text selectors.
- Easily locate elements without any id/classNames.
Elements containing some text
text=Hello world
This will match all the elements containing this text inside them.
Elements containing exactly the same text
text="Hello world"
This will match all the elements containing exactly the same text ("Hello world"). E.g a "Hello world" button.
🦖 Pros:
- Supports a variety of use-cases as it is web-standard
- Every major browser provides great tooling to play with CSS selectors.
CSS Selectors are the standard and powerful way to match elements for web applications. Crusher supports all the CSS selectors available, some of which are listed below with their use cases,
- Selector for elements by className:
.button
will select all items with the "button" class. - Selector for elements by Id:
#bookingButton
will select the element with id "bookingButton" - Selector for elements by tags:
div
will select all div tag elements. - Selector for elements by attributes:
button[clickable=true]
will select all buttons with the attribute "clickable" set to true. - Selector for elements with relationships:
#container .button
will select all the.button
elements inside the#container
element. - Selector with different combinations:
div#container .button[clickable=true]
will select all the.button
elements with clickable attribute to true inside#container
which isdiv
.
If you want to know more about CSS selectors, Mozilla provides excellent documentation https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
//button[@class='button']
: This xPath will select all items with the "button" class.//button[@id='button']
: This xPath will select elements with the id "button"//div
: This will select div elements//div/button[@class='button'][clickable="true"]
: This will select the button element having ".button" class and clickable set to "true" inside the div.//button[text()="Hello world"]
: This will select the button with text "Hello world"//.button[3]
: Select the third element with ".button" class
Here's the cheatsheet for XPath, if you are interested in going deeper https://devhints.io/xpath