Selenium ExpectedConditions: How to Wait in Your Test

Selenium is one of the most prominent choices when people need a test automation tool. Well, strictly speaking, Selenium is…

Testim
By Testim,

Selenium is one of the most prominent choices when people need a test automation tool. Well, strictly speaking, Selenium is a browser automation tool. But more often than not, people end up using the automation power of Selenium to perform complex end-to-end testing. When doing such tests, you often need to use wait commands. This post is all about a particular wait feature in Selenium, Selenium ExpectedConditions.

We’ll structure the post in two main parts. The first one is about fundamentals. We’ll start with a brief overview of Selenium. After that, we’ll explain what waits are and why they’re so important. Finally, we’ll offer a brief introduction to ExpectedConditions in Selenium, including an example. Here’s a summary of the points we’ll cover:

  • Selenium ExpectedConditions: What Is It All About?
    • A Quick Overview of Selenium WebDriver
    • What Are Wait Commands in Selenium, and Why Do They Matter?
    • Types of Waits
    • Explicit Waits In Selenium
  • Advantages of ExpectedConditions
  • Selenium ExpectedConditions: an Example in Java
    • Obtaining the Requirements
    • Starting the Example
    • Adding a Wait Using ExpectedConditions
  • What Are the Other Expected Conditions?
  • Test Automation: There Is Life After Selenium

Let’s get started.

Selenium ExpectedConditions: What Is It All About?

Before we show you how to use Selenium ExpectedConditions features, let’s start with some basics on Selenium itself.

A Quick Overview of Selenium WebDriver

Selenium comes in three main versions. Selenium IDE is a browser extension you use to create simple record-and-playback tests. If you need to do grid testing—i.e., testing across different browsers and operating systems—then Selenium Grid is the flavor of Selenium that can help you.

But when you think “Selenium,” you’re probably thinking of Selenium WebDriver. This is the third and most powerful version of Selenium, which allows you to drive—that is, to control—the browser in complex ways. Rather than being a tool, Selenium is more like an API that supports several programming languages. You pick your favorite language from the pool of supported languages and write your interactions.

What Are Wait Commands in Selenium, and Why Do They Matter?

When you’re writing testing scripts that exercise a web app through its UI, you often run into time-related issues. That happens because different elements on the page may load at different times. If you try to interact with an element—for instance, by clicking a button—when that element isn’t visible yet, your test script will fail.

That’s where wait commands come in handy. They allow you to instruct your test script to wait for a certain amount of time before progressing. So, wait commands are essential to ensure you test your web application in a way that’s as close as possible to how a real user would.

Types of Waits

The different wait commands available in Selenium can be split into two main categories: implicit waits and explicit waits. (There is a third category, fluent waits, but you could argue that they’re a specialized type of explicit waits.)

Implicit waits allow your test script to wait for a specific amount of time before going on.

Explicit Waits In Selenium

Explicit waits are more flexible. They enable you to wait until certain expectations are met. For instance, you can instruct your test to wait until a given button becomes visible, a text file receives a certain string of text, or a given element is no longer present.

Selenium ExpectedConditions is the feature of Selenium WebDriver that allows you to use explicit waits. There is a long list of expected conditions you can use, and you’ll see some of them up next.

Advantages of ExpectedConditions

As we’ve said, SeleniumExpectedConditions is Selenium’s way of providing explicit waits. And why are explicit waits a desirable feature?

Explicit waits—and, thus, expectedconditions—are better than implicit ones because they’re more flexible and more performant. Since you’re waiting on a specific situation to happen, you gain two big benefits.

First, you don’t run the risk of performing your action before the condition is really valid, which may occur if you just wait for a fixed amount of time.

Secondly, you don’t have to wait an unnecessary amount of time, since the action is triggered as soon as the condition becomes true. So, expected conditions are both more reliable and more performant than using implicit waits.

Selenium ExpectedConditions: an Example in Java

The first part of the post is over. You now understand what ExpectedConditions in Selenium are and why they matter so much when writing tests using this automation tool.

With the “what” and “why” out of the way, it’s time to focus on the “how” by showing some examples of what ExpectConditions look like in practice. Before that, though, let’s cover what requirements you’ll need to follow along with the examples.

Obtaining the Requirements

Though Selenium WebDriver works with many languages, we’ll use Java in this tutorial. To follow along, you’ll need to have the Java SDK installed, as well as Maven.

Selenium WebDriver itself is distributed as an executable, according to your browser and operating system. Click here to download the driver for the Chrome browser. Make sure you download the driver that matches the version of Chrome you have installed. After downloading the executable, save it somewhere and add its location to the system’s path. You’ll need an IDE or text editor in which to write the code. Though I’ll use the free Visual Studio Code, you’re welcome to use whatever editor or IDE you’re most comfortable with.

After everything is in place, start a new Java project using Maven as the build system. Add the following to your pom.xml file:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-chrome-driver</artifactId>
    <version>3.14.0</version>
</dependency>

 

Starting the Example

Let’s start our example. We’ll navigate to Testim’s site, click on a link that will take us to another page. There, we’ll retrieve the text of an element that contains the contact email.

We’ll start by adding the imports we’ll need:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

Now for the actual code. This is what the main method should look like:

public static void main(String [] args){
        WebDriver driver = new ChromeDriver();
        driver.get("https://testim.io");   
        WebElement button = driver.findElement(By.xpath("//div[@class='btn-group']/a[2]"));
        button.click();
        WebElement email = driver.findElement(By.className("contact-email"));
        String emailAddress = email.getText();
        System.out.println(emailAddress);
} 

Let’s explain what the code above does. In the first line, we instantiate a new instance of the ChromeDriver class, assigning it to a variable named “driver.” With this driver object, we navigate to Testim’s site (https://testim.io).

After accessing the site, we then use XPath to retrieve the button we want. The “button” is actually a link, specifically the second link inside the div, which has the class btn-group.

We then perform a click on the button. That brings us to yet another page, where we want to retrieve the text from the element with the class contact-email. After doing so, we print the obtained text to the console.

Adding a Wait Using ExpectedConditions

The example above works perfectly. But let’s imagine that the element with the contact email took some amount of time to become visible. That would create the need for us to wait. As mentioned, wait commands in Selenium come in two main categories: implicit and explicit.

The explicit waits are the ones we want to use here. They allow us to instruct our script to wait until certain conditions are met. How would we change our example to introduce an explicit wait?

Here’s the new version using ExpectedConditions:

WebDriver driver = new ChromeDriver();
driver.get("http://testim.io");   
WebElement button = driver.findElement(By.xpath("//div[@class='btn-group']/a[2]"));
button.click();

WebElement email = new WebDriverWait(driver, 10)
    .until(ExpectedConditions.elementToBeClickable(By.className("contact-email")));

String emailAddress = email.getText();
System.out.println(emailAddress);

In this new version of the code, we use a new object from type WebDriverWait. We pass both our driver and a timeout value in seconds and then use Selenium ExpectedConditions to define that our script should wait until the element identified by the class name contact-email becomes clickable.

Types of ExpectedConditions

The list of all the possible conditions you can wait on is long. Besides that, it varies according to the language binding you’re using. Here are just a few:

  • alert is present
  • element exists
  • element is visible
  • title contains
  • element is clickable
  • title is
  • element staleness
  • element is selected
  • visible text

To see all of the available conditions for Java, refer to the ExpectedCondition class documentation. Though walking you through all expected conditions is way outside the scope of this post, we will cover some of them in more detail, detailing their syntax and explaining their usage.

Title Contains

The title contains expected condition allows you to check whether an element’s title contains the string you specify. Here’s the method syntax:

public static ExpectedCondition<Boolean> titleContains​(String title)

Keep in mind that the string you provide is case-sensitive.

Title Is

This condition is similar to the “title contains” one. However, unlike its previous counterpart, it requires an exact match for the title of a page. Here’s the syntax:

public static ExpectedCondition<Boolean> titleContains​(String title)

Element To Be Selected

This condition expects a given element to be selected. This is the method’s syntax:

public static ExpectedCondition<Boolean> elementToBeSelected​(WebElement element)

Test Automation: There Is Life After Selenium

In today’s post, we’ve covered ExpectedConditions in Selenium. You’ve learned about the importance of waits in automated web testing.

As it turns out, though, Selenium isn’t the only alternative when it comes to automated end-to-end tests in web applications. Despite its popularity and many advantages, the tool also has its cons, such as the tendency to generate flaky tests.

Testim Automate is an AI-powered test automation tool you can use to create tests that are more robust and don’t result in heavy test maintenance. Testim Automate also offers several types of wait you can leverage in your testing.

Create a free Testim account today to give it a try.

What to read next

How to Fix Selenium’s Element Is Not Clickable at Point

How to Check If an Element Exists in Selenium