1

Using selenium webdriver to test if the button is not visible the boolean is always returning true.

using below code and returns TRUE,in web page I can see the xpath for Add button. Button is not visible.

    boolean present;  
    try { 
        //driver.findElement(By.xpath("//button[@id='add']")); 
        driver.findElement(By.xpath("//button[@id='add']")).isDisplayed();
       present = true;
       System.out.println("Add button is present");   
    } catch (NoSuchElementException e) { 
       present = false;
       System.out.println("Add button is not present:" +e.getMessage()); 
}

xpath: addButtonxpath

KunduK
  • 32,888
  • 5
  • 17
  • 41
shobha
  • 11
  • 2

3 Answers3

0

This is correct behaviour

driver.findElement(By.xpath("//button[@id='add']")).isDisplayed(); this will return as false however you have explicitly define present = true; in next line.

What you could do use if..else block

        boolean present;  
        if (driver.findElement(By.xpath("//button[@id='add']")).isDisplayed())
        {
            present=true;
            System.out.println("Add button is present");  
        }
        else
        {
            present = false;
            System.out.println("Add button is Not present");  
        }
KunduK
  • 32,888
  • 5
  • 17
  • 41
0

Here is the code snippet

boolean present;
try {
    present = driver.findElement(By.xpath("//button[@id='add']")).isDisplayed();
    System.out.println("Add button is present");
} catch (NoSuchElementException e) {
    present = false;
    System.out.println("Add button is not present:" + e.getMessage());
} catch (Exception e) {
    present = false;
    System.out.println("Add button is not present:" + e.getMessage());
}
Rahul Das
  • 46
  • 6
  • still getting Add button is present – shobha Mar 09 '21 at 16:41
  • May be element present in the DOM, Is there more than one Add button present in the DOM, you could check for the visibility: visible; attribute, get the visibility attribute value and check if its hidden – Rahul Das Mar 10 '21 at 04:13
  • Only one button and I checked the element its not tagged as hidden – shobha Mar 12 '21 at 11:20
0

Working of isDisplayed() method is doubtful and topic of debate. Having said that in your case isDisplayed() is not working because it is getting element in the DOM and returning true even though the element is not visible on the UI.

There is style attribute in the DOM for this button by checking that you can be on the conclusion. Like -

driver.findElement(By.xpath("//button[@id='add' and @style='display:none;']")

Now enable the button and check the style property, It will be changed to something else use that value and create xpath using that. and Check for add button elements presence. Then your isDisplayed() method may work as intended.

Dev
  • 2,739
  • 2
  • 21
  • 34
  • 1
    Thank you! it worked when i gave the xpath as "//button[@id='add' and @style='display:none;']" – shobha Mar 16 '21 at 14:18