Implementing an extension for the WebElement object to highlight elements

During the test execution, there is no way to highlight an element. This will help us to see what is actually going on in the browser. This method will slow down the tests a bit, but sometimes it's a useful way to debug tests.

In this recipe, we will create an extension for WebElement and provide the highlight Elements() method at runtime.

Getting ready

Create a new Java class file for the WebElementExtender.java class, or you can use the class created in the previous recipe.

How to do it...

Add the highlightElement() method to the WebElementExtender class, as follows:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsDriver;

public class WebElementExtender {

   public static void highlightElement(WebElement element) {
      for (int i = 0; i < 5; i++) {
        WrapsDriver wrappedElement = (WrapsDriver) element;
        JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver();
        driver.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                  element, "color: green; border: 2px solid yellow;");
        driver.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                  element, "");
      }
  }
}

How it works...

In the highlightElement() method, we created an instance of the JavaScriptExecutor class and, from the element, got an instance of the WrappedDriver class on which we wanted to call the highlightElement() method.

Using the JavaScriptExecutor class, we called the JavaScript setAttribute() method to set the style attribute value to green and then back to original. We do this a few times using a loop. During execution, the element is highlighted with a green flash. Here is an example on using the highlightElement() method:

WebElement userName = driver.findElement(By.id("username"));
WebElementExtender.highlightElement(userName);
userName.sendKeys("test_user");

This comes in very handy while debugging or visualizing the test progress.

See also

  • The Implementing an extension for the WebElement object to set the element attribute values recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.14.200