Sunday, October 25, 2015

Simplify Locators with HTML Data Attributes


Back in September, during the 2015 Selenium Conference, I presented the concept of using data-* attributes during a lightning talk. And again during Nashville's Selenium Users Group Meetup the following week. Sharing my experience with creating simple locators against an Angular SPA. Although the concept is not revolutionary, it seem new to most individuals. Many struggling trying to find a solution that does not leave them with brittle locators.

Despite the fact that there are a number of test frameworks that offer support for heavy-laden JavaScript applications, many relying on the internals of that JavaScript framework to create locators -- But the questions I ask, "Should your locators become coupled to your Javascript framework? What happens when developers move on to the next framework? Will it require a rewrite of your locators?

By implementing data attributes, allows the QA engineer the freedom to name the attribute, along with its value to something meaningful within the test. And at the same time, is not dependent on any external framework. Thus, leaving the idea that if the underlaying JavaScript framework changes, the locator is not impacted nor should the test itself.


Examples:

CSS - By.cssSelector(“[data-qa-hook=‘category.name.label’]”);
XPath - By.xpath(“//*[@data-qa-hook=‘category.textbox’]”);
JS - document.querySelectorAll(“[data-qa-hook='category.button']");



2 comments:

  1. Hi Shawn, Thank you for the post. May I ask one question, who will add this Data Attributes to webpage and when ?

    ReplyDelete
  2. who? that is based on your team -- on mine, I do it. When? I will add them when I start the automation task. In addition, I use a standard naming convention. example if there is a field for email, I would use: data-qa-hook="email.textbox"

    ReplyDelete