[Tip] How to verify element.style properties

Using WebUI, there is no direct way to verify/check the style properties of an HTML element. Some users have tried using verifyElement(Not)HasAttribute() - the problem with that is, the style property is not an HTML attribute. Perhaps even worse, the style property has its own properties!

The only reasonable way to test style property values is to use JavaScript.

In Groovy, you can execute a block of JavaScript code using the WebUI method, executeJavaScript()

WebUI.executeJavaScript('alert("Hello, JavaScript!")', null)

You can also pass variables/parameters to the JavaScript:

String name = "Batman"
WebUI.executeJavaScript("console.log('Hello, ${name}!')", null)
// Or...
WebUI.executeJavaScript("console.log('Hello, ' + arguments[0] + '!')", Arrays.asList(name))

These two calls to JavaScript output their results to the browser console.

The following JavaScript code retrieves the top coordinate of an element and fails the test if the coordinate is not 100px:

WebElement element = WebUiCommonHelper.findWebElement(findTestObject('your/test_object'), 10)
String js = "return arguments[0].style.top;"
String top = WebUI.executeJavaScript(js, Arrays.asList(element))
if(top != "100px") {
  KeywordUtil.markFailed("Top coord is " + top + " but should be 100px")
}

The following test does the same thing but this time it uses a CSS selector to target the element which shows you how to use the JavaScript without creating a TestObject. The element is a div with id=“my-div”.

String js = "return document.querySelector('#my-div').style.top;"
String top = WebUI.executeJavaScript(js, null)
if(top != "100px") {
  KeywordUtil.markFailed("Top coord is " + top + " but should be 100px")
}

Finally, here is a rudimentary Custom Keyword method to validate arbitrary style property values:

static void verifyStyleProperty(TestObject to, String propertyName, String expectedValue) {
  WebElement element = WebUiCommonHelper.findWebElement(to, 10)
  String js = "return arguments[0].style.${propertyName};"
  String value = WebUI.executeJavaScript(js, Arrays.asList(element))
  if(value != expectedValue) {
    KeywordUtil.markFailed("Style property is " + value + " but should be " + expectedValue)
  }
}

You can call the method like this:

import static your_package.*

verifyStyleProperty(findTestObject("your/test_object"), "width", "500px")

verifyStyleProperty(findTestObject("your/other_test_object"), "display", "none")

2 Likes