Currently, I am working on creating user interface tests using selenium and I came across a method that is supposed to handle non-existing elements and hidden elements.
The issue arises in the second catch block where the method consistently returns 'true' even when the element is not displayed or hidden (visibility: hidden).
public boolean checkElementPresence(By locator, WebDriver driver) {
WebElement element = null;
try {
element = this.findElement(locator, 10, driver);
} catch (TimeoutException te) {
System.out.println("Timeout - This element could not be found: " + locator.toString());
return false;
}
catch (ElementNotVisibleException env) {
System.out.println("This element was found but is not visible: " + locator.toString());
return false;
}
if (element == null ) {
return false;
} else {
return true;
}
}
public WebElement findElement(By locator, int timeout, WebDriver driver) {
System.out.println("Calling findElement method: " + locator.toString());
int interval = 5;
if (timeout <= 20)
interval = 3;
if (timeout <= 10)
interval = 2;
if (timeout <= 4)
interval = 1;
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(timeout, TimeUnit.SECONDS)
.pollingEvery(interval, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
WebElement webElement = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
return webElement;
}
If anyone has suggestions on how to modify this code to detect hidden existing elements, I would greatly appreciate it. Thank you!