yeshujs

Apr 20, 20224 min

Wait commands in Selenium

Updated: Apr 21, 2022

One of the important concept in Selenium WebDriver is understanding Selenium Wait commands. While writing your selenium program, you might have come across wait commands. But, do you know what exactly Selenium waits is?

Well, waits in selenium is an essential piece of code that is required to execute a test case. In this article aims to get a brief insight into different types of wait commands that are widely used in practice.

Below are the topics to be covered in this article

  • What is Selenium Waits?

  • Types of Waits

  • Implicit Wait in Selenium

  • Explicit Wait in Selenium

  • Fluent Wait in Selenium

  • Implicit vs Explicit Waits

What is Selenium Waits?

Waits in Selenium is one of the important pieces of code that executes a test case. The test execution is a RACE between the loading page and automation code execution. The webpage has to load before the execution of the related automation script statement for a successful test run.

If this doesn’t happen, code just breaks! If an element is not located then the “ElementNotVisibleException” appears.

Selenium wait runs on certain commands called scripts that make a page load through it. Selenium Waits makes the pages less vigorous and reliable.

Now let’s move further and understand different types of waits.

Types of Waits

Selenium supports 2 types of waits and they are as follows

  1. Implicit Wait

  2. Explicit Wait

These wait types are there to handle this synchronization issue in Selenium WebDriver. You can find the details and difference between each one of them below.

Implicit Wait in Selenium

Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs. Once the command is in place, Implicit Wait stays in place for the entire duration for which the browser is open. It’s default setting is 0, and the specific wait time needs to be set by the following protocol.

To add implicit waits in test scripts, import the following package.

Package implicitWait;
 
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.*;
 
import org.openqa.selenium.chrome.chromeDriver;
 
import org.testng.annotations.AfterMethod;
 
import org.testng.annotations.BeforeMethod;
 
import org.testng.annotations.Test;
 

 
public class WaitTest {
 
private WebDriver driver;
 
private String baseUrl;
 
private WebElement element;
 
@BeforeMethod
 
public void setUp() throws Exception {
 
driver = new ChromeDriver();
 
baseUrl = "http://www.google.com";
 
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 
}
 
@Test
 
public void testUntitled() throws Exception {
 
driver.get(baseUrl);
 
element = driver.findElement(By.id("lst-ib"));
 
element.sendKeys("Testing Implicit Wait");
 
element.sendKeys(Keys.RETURN);List<WebElement> list = driver.findElements(By.className("_Rm"));
 
System.out.println(list.size());
 
}
 
@AfterMethod
 
public void tearDown() throws Exception {
 
driver.quit();
 
}
 
}

It is written once and applicable throughout the same instance of WebDriver during execution. The polling interval for finding the element is 500ms. If element is not located in specified wait time, after the timeout, it throws ElementNotVisibleException

//This is an example of implicit wait. This statement ensures that the execution waits for element to be visible for 30 seconds.
 
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Explicit Wait in Selenium

Explicit waits are used to halt the execution until the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, Explicit waits are applied for a particular instance only.

WebDriver introduces classes like WebDriverWait and ExpectedConditions to enforce Explicit waits into the test scripts.

Below is an example of Explicit

Package explicitWait;
 
import static org.junit.Assert.*;
 
import java.util.concurrent.TimeUnit;
 
import org.junit.After;
 
import org.junit.Before;
 
import org.junit.Test;
 
import org.openqa.selenium.By;
 
import org.openqa.selenium.WebDriver;
 
import org.openqa.selenium.WebElement;
 
import org.openqa.selenium.chrome.ChromeDriver;
 
import org.openqa.selenium.support.ui.ExpectedConditions;
 
import org.openqa.selenium.support.ui.WebDriverWait;
 

 
public class explicitWait {
 
// created reference variable for WebDriver
 
WebDriver drv;
 
@Before
 
public void setup() throws InterruptedException {
 
// initializing drv variable using ChromeDriver
 
drv=new ChromeDriver();
 
// launching gmail.com on the browser
 
drv.get("https://gmail.com");
 
// maximized the browser window
 
drv.manage().window().maximize();
 
drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 
}
 
@Test
 
public void test() throws InterruptedException {
 
// saving the GUI element reference into a "username" variable of WebElement type
 
WebElement username = drv.findElement(By.id("Email"));
 
// entering username
 
username.sendKeys("Test Explicit");
 
// entering password
 
drv.findElement(By.id("Passwd")).sendKeys("password");
 
// clicking signin button
 
drv.findElement(By.id("signIn")).click();
 
// explicit wait - to wait for the compose button to be click-able
 
WebDriverWait wait = new WebDriverWait(drv,30);
 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));
 
// click on the compose button as soon as the "compose" button is visible
 
drv.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
 
}
 
@After
 
public void teardown() {
 
// closes all the browser windows opened by web driver
 
drv.quit();
 
}
 
}

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

Explicit Waits also known as Dynamic Waits because it is highly specific conditioned. In order to declare explicit wait, one has to use “ExpectedConditions”. The following Expected Conditions can be used in Explicit Wait,

  • alertIsPresent()

  • elementSelectionStateToBe()

  • elementToBeClickable()

  • elementToBeSelected()

  • frameToBeAvaliableAndSwitchToIt()

  • invisibilityOfTheElementLocated()

  • invisibilityOfElementWithText()

  • presenceOfAllElementsLocatedBy()

  • presenceOfElementLocated()

  • textToBePresentInElement()

  • textToBePresentInElementLocated()

  • textToBePresentInElementValue()

  • titleIs()

  • titleContains()

  • visibilityOf()

  • visibilityOfAllElements()

  • visibilityOfAllElementsLocatedBy()

  • visibilityOfElementLocated()

Fluent Wait in Selenium

Fluent Wait is quite similar to explicit Wait. It is similar in terms of management and functioning. In Fluent Wait, you can perform wait for action for an element only when you are unaware of the time it might take to be clickable or visible. Few differential factors that Fluent offers are as follows:

The pooling frequency

The pooling frequency in the case of Explicit is 500 milliseconds. But, using Fluent Wait, this pooling frequency can be changed to any value based upon your need. This usually means telling the script to keep an eye on the element after every 'x' seconds.

Ignore Exception

While pooling, if an element is not found, you can ignore some expectations like 'NoSuchElement'. Apart from this factor, similar to Explicit and Implicit Wait, you can define the amount of time for the element to be actionable or visible.

Syntax:

//This is an example of ifluent wait.
 
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
 
.withTimeout(60, SECONDS)
 
// this defines the total amount of time to wait
 

 
.pollingEvery(2, SECONDS)
 
// this defines the polling frequency
 

 
.ignoring(NoSuchElementException.class);
 
// this defines the exception to ignore
 

 
WebElement fw = fluentWait.until(new Function<WebDriver,WebElement>() {
 
public WebElement apply(WebDriver driver)
 
//in this method defined your own subjected conditions for which we need to wait
 
{
 
return driver.findElement(By.id("fw"));
 
}
 
});

Implicit v/s Explicit Wait

  1. Implicit Wait applies to all the elements in the script, while Explicit Wait is applicable only for those values which are to be defined by the user.

  2. Implicit Wait needs specifying "ExpectedConditions" on the located element, while Explicit Wait doesn't need to be specified with this condition.

  3. Implicit Wait needs time frame specification in terms of methods like element visibility, clickable element, and the elements that are to be selected. In contrast, Explicit Wait is dynamic and needs no such specifications.

Conclusion

In this Implicit and Explicit Wait in Selenium WebDriver article, we tried to make you acquainted with the WebDriver’s waits. We discussed and exercised both explicit and the implicit waits along with fluent wait.

    8880
    0