2

In my UI tests I would like to verify particular style values for the elements. Below is the example list of the styles I'd like to verify:

  • font style
  • font size
  • padding
  • margin

Is there a way to do that using Selenium?

  • 2
    Your question is too broad, make it more specific. Ask seperate questions. Give more context and explain what you tried already. Read how to ask questions: sqa.stackexchange.com/help/how-to-ask – Niels van Reijmersdal Aug 13 '18 at 12:43
  • @NielsvanReijmersdal why too broad? Isn't the question specific: How to test style attributes with Selenium? – beatngu13 Sep 19 '18 at 13:35
  • The edited question is better, it removed images, the original question also used to the word "like" a couple of times. – Niels van Reijmersdal Sep 19 '18 at 19:37
3

Selenium does not let you pick the current style of an element unless it is specified in style attribute of that element. However you can use JavaScript to pick any evaluated style of the element and pass it to your Selenium script.

Below is the example for Java:

    driver.get("https://www.w3schools.com");
    WebElement el = driver.findElement(By.xpath("//a[text()='LEARN HTML']"));
    String contents = (String) ((JavascriptExecutor) driver)
            .executeScript("return window.getComputedStyle(arguments[0]).getPropertyValue('background-color');", el);
    System.out.println(contents);
    driver.close();
1

There’s recheck-web (disclaimer: I work for retest, the company behind the open-source project). recheck replaces asserts and checks everything at once, including CSS attributes. It operates on top of Selenium and currently offers a Java API:

@Test
public void index() throws Exception {
    // Set the file name of the Golden Master.
    re.startTest( "my-file-name" );

    // Do your Selenium stuff.
    driver.get( "https://my-url.org/" );

    // Single call instead of multiple assertions (doesn't fail on differences).
    re.check( driver, "my-step-name" );

    // Conclude the test case (fails on differences).
    re.capTest();
}

The library essentially follows the principles of Golden Master Testing and Whitelist Testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.