logo logo

Selenium Wait Methods (Chapter 4)

Selenium Wait Methods

In this 4th Selenium article, we will look at the Wait Method category. Wait Methods are a group of methods that pause execution between statements. Typically, Selenium executes statements fast which can lead to errors. Two common errors occur when executing the next statement:

  1. Before fully loading the page and
  2. Before an element is visible

In addition, wait complications also cause problems with our Test Scripts. A wait complication is an outside component that interferes with automation such as Networks, JavaScript Engine Performance, Machine Performance, Server Performance, and Server Location.

In some cases, Thread.sleep is implemented to resolve common errors and wait complications. However, it’s not reliable for wait complications and can slow down our test. As a result, Thread.sleep is not recommended for production code.

All Selenium Wait Methods are dynamic. Therefore, they will wait before executing the next statement or wait for the maximum time. Contrarily, Thread.sleep is not dynamic so it won’t execute the next statement if the statement is ready to be executed. It will wait for the entire assigned time because it’s a sleep method.

By the end of this article, you will read about pageLoadTimeOut, implicitWait, Explicit Wait, and FluentWait. Note: FluentWait is deprecated and setScriptTimeout is another wait method which sets the amount of time for an asynchronous script to finish. Code from this article is located on GitHub https://github.com/RexJonesII/TestProject-TestNG

Tutorial Chapters

  1. Browser Methods (Chapter 1)
  2. WebElement Methods (Chapter 2)
  3. Navigation Methods (Chapter 3)
  4. You’re here → Wait Methods (Chapter 4)
  5. Switch Methods (Chapter 5)
    • Switch To Frame
    • Switch To Alert
    • Switch To Window

Page Load Timeout

Page Load Timeout is responsible for setting the wait time for a page to load. It’s 1 of 3 built-in Selenium Wait Methods. The other 2 built-in wait methods are implicitlyWait and setScriptTimeout. Page Load Timeout returns a Timeouts interface and has 2 parameters:

  1. Time – timeout value
  2. Unit – time unit such as milliseconds, seconds, etc.

The following statement dynamically waits 5 seconds to load TestProject’s Home Page:

@Test
  public void loadTestProjectHomePage () {
    driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
    driver.get("https://testproject.io/");
  }

The syntax begins with driver.manage().timeouts():

  • driver – is an object for the WebDriver interface
  • manage – returns an Options interface
  • timeouts – returns the interface for managing driver timeouts

We see pageLoadTimeout() with parameters 5 as the timeout value and SECONDS as the TimeUnit. If the page took longer than 5 seconds to load then the Test Script would have Failed with a TimeoutException.

Implicit Wait

Implicit Wait determines the amount of time a driver should wait for an element. If a program has multiple elements with a driver instance then Selenium waits for each element. Selenium will only wait if the element is not immediately present. Respectively, the implicilyWait() method waits for all instances of a driver.

TestProject’s Sign In page is a good example to demonstrate Implicit Wait and Explicit Wait. Before the page is visible, a spinning TestProject icon indicates the page will soon load. The following shows a screenshot of the spinning icon and incomplete code to click the Forgot Password link:

TestProject Spinning Icon

@Test
  public void demoImplicitWait () {
    driver.get("https://testproject.io/");
    driver.findElement(By.id("menu-item-901")).click();
    driver.findElement(By.id("tp-forgot-password")).click();
  }

The Test Script failed to click the Forgot Password link due to a NoSuchElementException. Selenium executed the statements so fast and tried to click the link before loading the page. Notice the code does not contain a Selenium Wait Method. Here’s a screenshot of the Sign In page including the Forgot Password link and the NoSuchElementException.

TestProject Sign In Screen

Selenium Wait Methods - NoSuchElementException ImplicitWait

Let’s add the implicitylyWait() method to dynamically wait 5 seconds for the Sign In page to load. It includes the same parameters as pageLoadTimeout(5, TimeUnit.SECONDS)

@Test
public void demoImplicitWait () {
  driver.get("https://testproject.io/");
  driver.findElement(By.id("menu-item-901")).click();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.findElement(By.id("tp-forgot-password")).click();
}

TestProject Reset Password Page

Now, we see the Reset Password page after clicking the Forgot Password link.

Explicit Wait

Explicit Wait is used on 1 element at a time. Selenium pauses execution until time has expired or an expected condition is met using the WebDriverWait class. One of the syntaxes for WebDriverWait is WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);.

Selenium Wait Methods - ExplicitWait

Note: The 3rd WebDriverWait() constructor which includes Clock and Sleeper is deprecated.

We pass in the driver and number of seconds to represent the max amount of time before throwing an exception. Next, we write the object wait and dot operator followed by until. The statement will wait for an expected condition. Selenium offers many ExpectedConditions such as elementToBeClickable(), presenceOfElementLocated(), etc. The following code shows how to wait until the Forgot Password link is visible:

@Test
public void demoExplicitWait () {
  driver.get("https://testproject.io/");
  driver.findElement(By.id("menu-item-901")).click();
  
  WebDriverWait wait = new WebDriverWait(driver, 5);
  wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("tp-forgot-password")));
  driver.findElement(By.id("tp-forgot-password")).click();
}

This example uses ExpectedConditions.visibilityOfElementLocated() because it’s an expectation for checking that an element is visible. Notice how it receives a Locator parameter. The element is successfully located By id with a value of tp-forgot-password. Afterwards, the Forgot Password link is clicked when the page loads and the element becomes visible.

Fluent Wait

Fluent Waits are the core of explicit waits because WebDriverWait extends FluentWait. According to JavaDoc, the WebDriverWait class is a specialization of FluentWait that uses WebDriver instances.

Selenium Wait Methods - FluentWait

Nevertheless, FluentWait is also deprecated just like the 3rd WebDriverWait constructor.

FluentWait Constructors

Should We Use Implicit Wait, Explicit Wait, or Both?

It’s not wrong to use Implicit Wait, Explicit Wait, or both Wait Methods. However, it’s safer to mainly use Explicit Wait which comes with many ExpectedConditions. ExpectedConditions is a class that helps us write our own customized Explicit Wait statements. Implicit Wait can break Explicit Wait if used together because Implicit Wait lives for the entire driver object life.

The next article in this Selenium Method Category series is Switch Methods. It’s a group of methods that switch to alerts, windows, and frames. Stay tuned! 😎

About the author

Rex Jones II

Rex Jones II has a passion for sharing knowledge about testing software. His background is development but enjoys testing applications.

Rex is an author, trainer, consultant, and former Board of Director for User Group: Dallas / Fort Worth Mercury User Group (DFWMUG) and member of User Group: Dallas / Fort Worth Quality Assurance Association (DFWQAA). In addition, he is a Certified Software Tester Engineer (CSTE) and has a Test Management Approach (TMap) certification.

Recently, Rex created a social network that demonstrate automation videos. In addition to the social network, he has written 6 Programming / Automation books covering VBScript the programming language for QTP/UFT, Java, Selenium WebDriver, and TestNG.

✔️ YouTube https://www.youtube.com/c/RexJonesII/videos
✔️ Facebook http://facebook.com/JonesRexII
✔️ Twitter https://twitter.com/RexJonesII
✔️ GitHub https://github.com/RexJonesII/Free-Videos
✔️ LinkedIn https://www.linkedin.com/in/rexjones34/

Leave a Reply

FacebookLinkedInTwitterEmail