Selenium: Test if text is fully visible Selenium: Test if text is fully visible selenium selenium

Selenium: Test if text is fully visible


Here's a simple example using a jsFiddle that I created and Java/Selenium.

The HTML

<p id="1">lorum ipsum dolor sit amet</p><p id="2">lorum ipsum <div style="display:none">dolor sit amet</div></p>

The code

String expectedString = "lorum ipsum dolor sit amet";WebDriver driver = new FirefoxDriver();driver.get("https://jsfiddle.net/JeffC/t7scm8tg/1/");driver.switchTo().frame("result");String actual1 = driver.findElement(By.id("1")).getText().trim();String actual2 = driver.findElement(By.id("2")).getText().trim();System.out.println("actual1: " + actual1);System.out.println("actual2: " + actual2);System.out.println("PASS: " + expectedString.equals(actual1));System.out.println("PASS: " + expectedString.equals(actual2));

The output

actual1: lorum ipsum dolor sit ametactual2: lorum ipsumPASS: truePASS: false

Selenium won't return text that isn't visible to the user so all you need to do is compare what you get back with the expected string. If they aren't equal, then text is likely hidden.


Here is the JAVA Code to check if the Text inside the element is visible or not:

public boolean checkForText() {    boolean isVisible = false;    try {        // Start by searching the element first.  You can search by many ways.  eg. css, id, className etc..        WebElement element = webDriver.findElement(By.id("the elemnts' id"));        System.out.println("Element found");        // Check if the found element has the text you want.        if(element.getText().equals("lorum ipsum dolor sit amet")) {            System.out.println("Text inside element looks good");            isVisible = true;            //additionally, you can perform an action on the element            //e.g. element.click();        } else {            System.out.println("Text does not match");        }    } catch (NoSuchElementException e) {        // the method findElement throws an exception.        System.out.println("Element not found");    }    return isVisible;}    

This method will return true ONLY if the element is found, and its inside text corresponds the equals criteria i.e. the text passed as parameter - lorum ipsum dolor sit amet

Hope this helps ;)


Following is one way of doing this if you use Java.

First, locate element with correct locator and do getText() and then compare the string with expected (full text).

driver.findElement(By.cssSelector("")).getText().equals("");

May be something like this:

String actual = driver.findElement(By.cssSelector("")).getText().trim();assertEquals(actual, expected);