Wait in Selenium Webdriver

Wait in Selenium Webdriver

Table of Contents

The wait functions are important when it comes to execute Selenium tests. They might help to observe and troubleshoot issues that may occur due to variation in a time lag.

In automation testing, wait commands instructs the test execution to pause for a certain length of time before moving to the next step. This enables the WebDriver to check if one or more web elements are present/visible/clickable, etc.

Why do the users need Selenium Wait?

Most of the web applications are developed with Ajax and Javascript. When a web page loads on a browser, the various web elements may load at various time intervals.

This creates difficulty while identifying any element. Also, if an element is not located on the web page, then the “ElementNotVisibleException” appears. Selenium Wait commands helps in resolving this issue.

Selenium WebDriver provides three commands for implementing wait in tests:

  1. Implicit Wait.
  2. Explicit Wait.
  3. Fluent Wait.

Implicit Wait in Selenium:

Implicit Wait instructs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once the time is set, WebDriver will wait for the element before returning an exception.

Once the command is placed, Implicit Wait will stay in place for the entire duration for which the browser is open. The default setting is 0, and the specific wait time is set by the following protocol.

For adding implicit waits in test scripts, import the following package.

import java.util.concurrent.TimeUnit;

Syntax:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Add the above code in the test script. It will set an implicit wait after the initialization of the WebDriver instance variable.

Example Of Implicit Wait Command:

Package waitExample;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class WaitTest {
private WebDriver driver1;
private String baseUrl;
private WebElement element;
@BeforeMethod
public void setUp() throws Exception {
driver1 = new FirefoxDriver();
baseUrl = "http://www.google.com";
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testUntitled() throws Exception {
driver1.get(baseUrl);
element = driver1.findElement(By.id("lst-ib"));
element.sendKeys("Selenium WebDriver Interview questions");
element.sendKeys(Keys.RETURN);
List<WebElement> list = driver1.findElements(By.className("_Rm"));
System.out.println(list.size());
}
@AfterMethod
public void tearDown() throws Exception {
driver1.quit();
}
}

Implicit wait will increase the test script execution time. It makes each command to wait for the defined time before resuming test execution. If the application responds normally, the implicit wait can slow down the execution of test scripts.

Explicit Wait in Selenium:

In the Explicit Wait command, the WebDriver is instructed to wait until a specific condition occurs before executing the code.

Setting Explicit Wait is important in those cases where certain elements naturally take more time to load. If one sets an implicit wait command, the browser will wait for the same time span before loading every web element causing an unnecessary delay in executing the test script.

The explicit wait is more intelligent but can only be applied to specified elements. However, it improves implicit wait since it allows the program to pause for the dynamically loaded Ajax elements.

In order to declare the explicit wait, one has to use “ExpectedConditions”. The Conditions that can be used in Explicit Wait are:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

To use the Explicit Wait in test scripts, import the below packages into the script.

import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait

Then, you need to initialize A Wait Object using the WebDriverWait Class.

WebDriverWait wait = new WebDriverWait(driver,30);

Here, the reference variable is named as <wait> for the <WebDriverWait> class. It is instantiated using the WebDriver instance. The maximum wait time needs to be set for the execution to layoff. The wait time is measured in seconds.

Example of Explicit Wait Command:

In the below example, the test script is for logging into “gmail.com” with a username and password. After a successful login, the code will wait for the “compose” button to be available on the home page. Finally, it will click on the button.

package waitExample;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ExpectedConditionExample {
// create a reference variable for WebDriver
WebDriver driver1;
@BeforeMethod
public void setup() throws InterruptedException {
// initialize the driver variable using FirefoxDriver
driver1=new FirefoxDriver();
// launch gmail.com on the browser
driver1.get("https://gmail.com");
// maximize the browser window
driver1.manage().window().maximize();
driver1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void test() throws InterruptedException {
// save the GUI element reference into a "element" variable of WebElement type
WebElement element = driver1.findElement(By.id("Email"));
// enter the username
element.sendKeys("[email protected]");
element.sendKeys(Keys.RETURN);
// enter the password
driver1.findElement(By.id("Passwd")).sendKeys("password");
// click on signin button
driver1.findElement(By.id("signIn")).click();
// explicit wait - will wait for the compose button to be available to click
WebDriverWait wait1 = new WebDriverWait(driver,30);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));
// will click on the compose button when the "compose" button is visible on the web page
driver1.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
}
@AfterMethod
public void teardown() {
// it will close all the browser windows opened by web driver
driver1.quit();
}
}

The above code will instruct the Selenium WebDriver to wait for 30 seconds before throwing a TimeoutException. If the Selenium WebDriver finds the element before 30 seconds, then it will return immediately. After that, it will then click on the “Compose” button. In Explicit Wait, the program will not wait for the complete 30 seconds, thus saving time and executing the script faster.

Fluent Wait in Selenium:

The Fluent Wait command describes the maximum amount of time for Selenium WebDriver to wait for a certain condition to appear. It also describes the frequency with which WebDriver will check if the condition appears before throwing the exception “ElementNotVisibleException.”

Fluent Wait simply looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.

Fluent Wait commands are useful while interacting with web elements that can sometimes take more time than usual to load. This is something that occurs in Ajax applications.

While using the Fluent Wait, it is possible to set a default polling period as needed. The user can easily configure the wait to ignore any exceptions during the polling period.

Syntax:

Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);
WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});

Example of Fluent Wait Command:

Wait wait = new FluentWait<WebDriver>(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingevery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

The above command operates with two primary parameters: timeout value and polling frequency. The above code contains time out value as 50 seconds and polling frequency as 3 seconds. It directs the WebDriver to wait for a maximum of 50 seconds for verifying a specific condition. If the condition fulfills during those 50 seconds, it will perform the test script’s next step. If not, it will throw an “ElementNotVisibleException”.

Difference between Implicit and Explicit Wait:

Implicit WaitExplicit Wait
It applies to all elements in a test script.It applies only to specific elements as intended by the user.
There is no need to specify “ExpectedConditions” on the element to be located.You must always specify “ExpectedConditions” on the element to be located.
It is most effective when used in a test case where the elements are located within the time frame specified in implicit wait.It is most effective when used where the elements are taking a long time to load. They are also useful for verifying property of the element such as visibilityOfElementLocated, elementToBeClickable,elementToBeSelected.

2 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class