App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide Understanding ExpectedConditions in Selenium (with Types and Examples)

Understanding ExpectedConditions in Selenium (with Types and Examples)

By Neha Vaidya, Community Contributor -

If you have understood Wait Commands in Selenium Webdriver, you might know what Expectedconditions are. However, if you haven’t read the article, it would help to do so before learning about Expectedconditions in Selenium. This article will explain Expectedconditions commonly used in Selenium with examples.

What is Expectedconditions in Selenium WebDriver?

Selenium WebDriver allows for waiting for specific conditions until a defined task is complete. An example is automating the task to check if all elements present on a web page, matching a particular locator, are visible.

Syntax:

static ExpectedCondition<WebElement> 
visibilityOfElementLocated(By locator)

Now, let us explore the various types of Selenium Expectedconditions and their uses.

Types of Expectedconditions

ExpectedCondition < WebElement >

This condition has a web element locator as a parameter. An explicit wait can be applied to the condition that tries to find the web element in question. If the condition finds the element, it returns the element as a result. If not, the wait command tries the condition again after a short delay.

ExpectedCondition < Boolean >

This condition has a string parameter, and the wait command applies the condition to the parameter. If the result is true, then the value true is returned. If the result is false, the wait command tries the condition again after a short delay.

While the explicit wait applies to the expected condition, the condition code may generate various exceptions.

Let’s have a look at a few of the expected conditions:

1. static ExpectedCondition < WebElement > elementToBeClickable(By locator)
This condition is used to instruct a command to wait until the element is clickable by the locator.

2. static ExpectedCondition < Boolean > elementToBeSelected(By locator)
This condition instructs a command to wait until the locator selects the element.

3. static ExpectedCondition < WebElement > presenceOfElementLocated(By locator)
This condition instructs a command to wait until the element becomes visible or present.

4. static ExpectedCondition < Boolean > titleContains(String title)
This condition is used to instruct a command to check if the title of the web element or the webpage contains the specific String or the group of characters.

5. static ExpectedCondition < Boolean > titleIs(String title)
This condition is used to instruct a command to check whether the title is the String or the group of characters.

6.static ExpectedCondition < Boolean > urlToBe(String url)
This condition is used to instruct a command to check if the URL of the webpage matches the expected URL.

7. static ExpectedCondition < WebElement > visibilityOfElementLocated(By locator)
This condition instructs a command to wait until the element becomes visible.

To learn about this in greater detail, refer to this official source on ExpectedConditions

Example of Selenium Expectedconditions

The following example applies Expectedconditions to the Facebook login page.

import java.util.concurrent.TimeUnit;
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 ExpectedCondtionsExample{
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "Path of the driver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.facebook.com/");
WebElement fname= driver.findElement(By.name("fname"));
WebElement lname= driver.findElement(By.name("lname"));
sendKeys(driver, fname, 10, "Your_Name");
sendKeys(driver, lname, 20, "Your_Lastname");
WebElement forgotAccount= driver.findElement(By.linkText("Forgotten account?"));
clickOn(driver,forgotAccount, 10);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
//sendkeys method
public static void sendKeys(WebDriver driver1, WebElement element, int timeout, String value){
new WebDriverWait(driver1, timeout).until(ExpectedConditions.visibilityOf(element));
element.sendKeys(value);
}
//clickable method declared explicitly
public static void clickOn(WebDriver driver1, WebElement element, int timeout){
new WebDriverWait(driver1, timeout).until(ExpectedConditions.elementToBeClickable(element));// Expectedcondition for the element to be clickable
element.click();
}
}

The code has used Facebook sign-up credentials and located them. It has also created a generic function to make it available for all elements to provide Explicit wait. The code uses Expected Conditions for the visibility of Element. The driver will wait for 20 seconds to detect if the element is visible. Then, using the sendKeys() method, it will enter the credentials to log in.

Note: To use Expectedconditions in a Selenium script, import the following packages:

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

Now, let’s understand how to create a Custom Expectedcondition in Selenium.

Custom Expectedcondition in Selenium

A Custom ExpectedCondition is a class that consists of a constructor with the parameters of the expected condition. It implements the ExpectedCondition interface and overrides the apply method.

The following example will demonstrate how to create a custom expectedcondition:

public class CustomConditionExample{

WebDriver driver; 
WebDriverWait wait;

By searchFieldXpath = By.id("twotabsearchtextbox");
By searchButtonXpath = By.className("nav-search-submit-text nav-sprite");

By resultLinkLocator = By.xpath("//span[@class='celwidget slot=SEARCH_RESULTS template=SEARCH_RESULTS widgetId=search-results index=0']//div[@class='a-section aok-relative s-image-fixed-height']"); 

String homeUrl = "https://www.amazon.com/"; 
String homeTitle = "Amazon.com: Online Shopping for Electronics, Apparel, Computers,...";

String resultsTitle = "Search | kindle paperwhite e-reader";
String resultsUrl = "https://www.amazon.com/s?k=kindle+paperwhite+e-reader";

@Before
public void setUp() }
driver = new FirefoxDriver();
wait = new WebDriverWait(driver, 10);
}
@After
public void tearDown() {
driver.quit();
}

@Test
public void test1() {
driver.get(siteUrl);

if (!wait.until(new PageLoaded(homeTitle, homeUrl)))
throw new RuntimeException("home page is not displayed");

WebElement searchField = wait.until(elementToBeClickable(searchFieldXpath));
searchField.click(); 
searchField.sendKeys(keyword);
WebElement searchButton = wait.until(elementToBeClickable(searchButtonXpath));
searchButton.click(); 

if (!wait.until(new PageLoaded(resultsTitle, resultsUrl)))
throw new RuntimeException("results page is not displayed");
}
}

public class PageLoaded implements ExpectedCondition { 
String expectedTitle;
String expectedUrl;

public PageLoaded(String expectedTitle, String expectedUrl) {
this.expectedTitle = expectedTitle; 
this.expectedUrl = expectedUrl;
}
@Override
public Boolean apply(WebDriver driver) { 
Boolean isTitleCorrect = driver.getTitle().contains(expectedTitle);
Boolean isUrlCorrect = driver.getCurrentUrl().contains(expectedUrl);
return isTitleCorrect && isUrlCorrect;
} 
}

Executing the above code, it will verify whether the home page URL and the result page URL match. Selenium will also check whether both URLs are displayed and wait until the page is loaded.

Advantages of Selenium Expectedconditions

  1. With explicit waits, more expected success conditions can be implemented.
  2. It allows the coder to wait for the presence or absence of elements/conditions.
  3. The timeout can be customized on every call.

That’s all about Selenium Expectedconditions. To know more about the fundamentals of Selenium WebDriver, look at this Selenium WebDriver Tutorial.

BrowserStack’s Selenium grid offers 3000+ real devices and browsers for automated testing. Users can run tests on multiple real devices and browsers by signing up, logging in, and selecting the required combinations.

Try Selenium Testing on Cloud

Also, explore what David Burns has to say about Selenium 4 features – which is the most preferred tool suite for automated cross-browser testing of web applications.

Understanding ExpectedConditions in Selenium (with Types and Examples)

Tags
Automation Testing Selenium Webdriver

Featured Articles

Locators in Selenium: A Detailed Guide

findElement and findElements in Selenium

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack