selenium implicit + Explicit + fluent waits

Every browser application has it's own delay in loading the elements when we open a web application / navigate from one page to another / perform some action.

Loading depends on different criteria like internet bandwidth, technology used in the application, server capacity, no of users accessing the browser app etc...

While executing tests in different machines/environments, we need to make sure our script or code should wait till the elements load/present on the web page to perform some action upon them...

Selenium provides different ways to wait for an element on web page...

let's see them one by one -


Hard waits

Thread.sleep(2000);
Irrespective of how much time an element takes time to load on web page, selenium waits for the amount of time as mentioned in the above line, in this case, 2sec (2000 millisec)

Implicit wait

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.qavalidation.com");

The above code will wait for 10 sec only to find any elements on the web page, and this time is fixed to wait for an element through out the code (until unless we rewrite the statement with different wait time).
As soon as found the element with in that time bound, performs action as coded,
else (if the time is over but not found), WebDriver throws exception (not able to locate the element)


This above code will wait for an element to locate only, but there are situations where we wish to wait for specific webelement property conditions like enabled, to be clickable, presence etc..., for this we can use explicit wait.


Explicit wait

By WebElement locator

WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.id("Inbox")));

In the above code,  ExpectedConditions will wait 30sec for an element (say Inbox in Gmail after login) to be clickable,
if before 30sec it will find the element to be clickable, then instead wait for 30sec to complete control goes to next code line.
same we have conditions like, elementtobevisible, presenceofanelement...if we enter a dot after ExpectedConditions, will get one by one element property to wait.

Fluent wait

There are situations where we want to wait for an element for specific time with our own polling time (how frequently) so selenium will locate an element.
WebElement element = fluentWait(By.id("Inbox"));

public WebElement fluentWait(By locator){
    Wait<webdriver> wait = new FluentWait<webdriver>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(5, TimeUnit.SECONDS)
        .ignoring(NoSuchElementException.class);

    WebElement foo = wait.until(
        new Function<webdriver webelement="">() {
            public WebElement apply(WebDriver driver) {
                return driver.findElement(locator);
            }
        }
    );
    return foo;
};


No comments:

Post a Comment