Skip to main content

How to Visually Verify Your Locators

Intro​

This is a pseudo guest post from Brian Goad. I've adapted one of his blog posts with his permission. You can see the original blog post here.

It's likely that you'll run into odd test behavior that makes you question the locators you're using in a test. But how do you interrogate your locators to make sure they are doing what you expect?

A Solution​

By leveraging some simple JavaScript and CSS styling, we can highlight the element on the page that we're targeting. This way we can visually inspect it to make sure it is the one that we want.

Let's take a look at an example.

Example​

We create a highlight helper that accepts an element and a time to keep it highlighted (e.g., a duration of 3 seconds by default). It does three things:

  1. It stores the style of the element, so it can revert it back when it's done.
  2. It changes the style of the element, so it visually stands out (e.g., a red dashed border).
  3. It reverts the style of the element back after the duration.

We're accomplishing the style change through JavaScript's setAttribute function, and we're executing it with Selenium. To use it in a test, we just pass it the element we found.

We use a page with a large DOM from the-internet. Our first test highlights an element without reverting it (a duration of 0) and checks that it has the border. The second one highlights it for 1 second and checks that the style was reverted.

Expected Behavior​

  1. Load the page
  2. Find the element
  3. Change the styling of the element, so it has a red dashed-line border
  4. Wait for the duration
  5. Revert the styling to remove the border

Summary​

Hopefully this tip helps you quickly confirm that your locators are targeting the elements you expect. Since it adds waiting time to your tests, use it while writing or debugging them, not in every run. If you wanted to take this a step further, you could combine it with an event listener, to highlight every element your test interacts with.

Happy Testing!

Special Thanks​

Roman Isko
Contributed the initial Java code for this tip.

Authors​

Brian Goad
Author of the original blog post this tip is adapted from
Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Elemental Selenium maintainer