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']");



6 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
  3. This is awesome and very helpful...thank you Shawn!

    ReplyDelete
  4. This is really great practice to follow. We are also trying to get our hands on element declaration.
    Can you please elaborate more on benefits of the naming convention that you follow?

    ReplyDelete
  5. Sorry Shawn, i didnt get this approach. We, as automation test engineers, didnt get chance to add attributes to elements of dom. Why? developers do it and deploy for testing. Do you mean that dev ppl should add this attribute? Can u pls help me to understand how this can be driven from testing team?

    ReplyDelete
  6. I usually suggest a developer for adding Data Attributes

    ReplyDelete