DEV Community

Cover image for Selenium Java (Implicit & Explicit) Waits
Anne Quinkenstein
Anne Quinkenstein

Posted on • Updated on

Selenium Java (Implicit & Explicit) Waits

If you enter Websites, you usually wait a few seconds if you see the information. If click, based on your input, which first goes to the backend, you see changes. You have to wait till the changes are done.

Implicit Wait - globally declared

Declare globaly:
"Hey Selenium, wait for n number of seconds before you throw exceptions!"
It listens to your DOM, if it displayed it will keep on.
n is the maximum time Limit

driver.manage().timeouts().implicitlyWait(5,limeUnit.SECONDS;
Enter fullscreen mode Exit fullscreen mode

Explicit Wait - targets a specific scenario

Imagine a search Button. When you search a large amount of targets, it takes, sets say 15 seconds to load.
Otherwise the Application should load faster.

WebDriverWait

Continuisly listen to DOM as well.

WebDriverWait w = new WebDriverWait(driver, 5)
w.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span.promoInfo")));
// or .elementToBeClickable .... 
Enter fullscreen mode Exit fullscreen mode

ExpectedConditions List

Fluent Wait

monitors at regular intervalls of time (Pollingtime has to defined)
Example: if something is displayed,which you don't want to check. (after 3 sec "Card is accepted" - "Order is process" after 7 sec - .... )

 Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofSeconds(5))
                .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(
//customised function - until methods returns webelement
new Function<WebDriver, WebElement>() {
 public WebElement apply(WebDriver driver) {
            if (driver.findElement(By.cssSelector("div#finishh4")).isDisplayed()){
             return driver.findElement(By.cssSelector("div#finish h4"));
            }
            else
            {
                return null;
            }
        }});
Enter fullscreen mode Exit fullscreen mode

Thread.Sleep

Part of Java, not specially Selenium
waits the amount of time, without listening to DOM

Top comments (0)