DEV Community

Selenium WebDriver and Dynamic Locators

Klaus on November 07, 2018

As we all know, functional testing scripts that run through the UI need stable locators in order to locate the elements. Selenium uses the followi...
Collapse
 
danielavalero profile image
Daniela Valero

Hello Klaus,

Recently in the Selenium IDE github, someone asked a valid question about Selectors and modern JS frameworks like react of vue: github.com/SeleniumHQ/selenium-ide...

Relevant for my question is:

As a result using ID for selectors is now considered a bad practice to select elements, and bad practice to create a page out of components (it's not unique most of the time).
...
Using these data-test selectors allows for less brittle tests, and they clearly signal that messing with a certain element can cause a test to fail.

At the end, they added: data-test and data-test-id to select as well elements.

Also, in the Selenium/WebDriver website they comment that there is support to select react components, based on their name: webdriver.io/docs/selectors.html#r...

As a passionate for automated testing, what's your view on this? Would you say that using these are a good alternative to use?

Greetings

Collapse
 
razgandeanu profile image
Klaus

Hi Daniela,
Thank you for taking the time to write that comment.
Yes, you can easily write a stable CSS Selector or XPath based on a certain attribute and the value of that attribute. It's ideal if you have an attribute like data-test or data-test-id, but very few web applications actually have those.
If someone would start a project from scratch, I would definitely encourage them to implement and use data-test or data-test-id attributes.

Collapse
 
danielavalero profile image
Daniela Valero

Hello Klaus, thanks a lot!

Collapse
 
mstrelex profile image
Marat Strelets

Is this approach faster than searching with xpath? such as

//*[@state = 'active']

Collapse
 
philnash profile image
Phil Nash

I feel like the code in this post doesn't show an example of when you would need to use this technique, however it shows how to use it.

I can imagine a scenario where none of the Selenium selector strategies would apply (perhaps it moves about in the source of the page and shares attributes and classes with other items on the page) but you still need to pin down your element and get an ID for it. This would work in that case.

I'm pretty sure that using Selenium's native selection methods are what you would choose unless you simply can't get your element using them.