Understanding ExpectedConditions in Selenium (with Types and Examples)

Learn how to use ExpectedConditions in Selenium to handle dynamic elements effectively. Explore types, syntax, and real-world usage examples.

Guide Banner Image
Home Guide Understanding ExpectedConditions in Selenium (with Types and Examples)

Understanding ExpectedConditions in Selenium (with Types and Examples)

When automating web applications with Selenium, waiting for elements to load properly is crucial. Expected Conditions in Selenium provide a reliable way to wait for specific states, like element visibility, clickability, or alerts, ensuring tests are stable and less flaky.

Overview

Types of Expected Conditions in Selenium

  • visibility_of_element_located: Waits until an element is visible on the page.
  • element_to_be_clickable: Waits until an element is visible and enabled.
  • presence_of_element_located: Waits for the presence of an element in the DOM.
  • text_to_be_present_in_element: Waits until specific text appears in a given element.
  • alert_is_present: Waits for an alert dialog to appear.
  • element_to_be_selected: Waits until an element (like a checkbox) is selected.
  • invisibility_of_element_located: Waits until the element is no longer visible or present.

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

Here are some of the types of Expected Conditions in Selenium:

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.

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, understand how to create a Custom Expectedcondition in Selenium.

Commonly Used Methods With ExpectedConditions

These methods frequently help synchronise tests with web page behaviour:

  • elementToBeClickable(By locator): Waits for an element to be visible and enabled before clicking.
  • visibilityOfElementLocated(By locator): Ensures an element is present and visible in the DOM.
  • presenceOfElementLocated(By locator): Confirms an element exists in the DOM regardless of visibility.
  • textToBePresentInElementLocated(By locator, String text): Waits until specific text appears inside an element.
  • titleIs(String title) / titleContains(String titleFragment): Checks for exact or partial matches in the page title.
  • alertIsPresent(): Detects JavaScript alerts or pop-ups.
  • frameToBeAvailableAndSwitchToIt(By locator): Switches to a frame once it is available.
  • invisibilityOfElementLocated(By locator): Waits for an element to disappear or become hidden.
  • stalenessOf(WebElement element): Waits for an element to detach from the DOM.
  • numberOfElementsToBe(By locator, int number): Verifies that a certain number of elements exist.

Talk to an Expert

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.

ExpectedCondition that can be used in Explicit Waits

Explicit waits leverage ExpectedConditions to pause test execution until a specified condition is met. Some additional useful conditions include:

  • numberOfWindowsToBe(int expectedNumberOfWindows): Waits until the browser opens the expected number of windows or tabs.
  • refreshed(ExpectedCondition<T> condition): Reapplies a condition after refreshing an element, useful to handle stale references.
  • urlToBe(String url) / urlContains(String fraction): Waits for exact or partial URL matches, confirming navigation success.
  • elementToBeSelected(By locator): Ensures a checkbox, radio button, or option is selected.
  • invisibilityOf(WebElement element): Confirms a specific WebElement is no longer visible, useful when you already have a reference.

Advantages of Selenium Expectedconditions

Selenium’s ExpectedConditions class, when applied with explicit waits, has multiple benefits that make the automated tests more reliable and efficient.

  • Improved Performance: By waiting for certain conditions (e.g., visibility, clickability), tests are less prone to fail because of timing, resulting in more stable and reliable results. Explicit waits enable tests to move forward immediately when the condition is satisfied, and they may minimize unnecessary waiting time over fixed waits.
  • Exact Control Over Wait Conditions: Testers can specify specific conditions to wait for, like element visibility or page title, providing greater control over test running.
  • Less Flakiness: Waiting for elements to become in a certain state before dealing with them assists in the avoidance of errors such as ElementNotVisibleException, leading to more reliable test outcomes.
  • More Transparent Test Intentions: Employing explicit waits with specified conditions clarifies the purpose of the test, enhancing code readability and maintainability.
  • Improved Dealing with Dynamic Content: Explicit waits are useful in situations where elements asynchronously load, for instance, with AJAX or JavaScript, so tests wait for elements to be available before they interact.

BrowserStack Automate Banner

Best Practices for using ExpectedCondition in Selenium

Here are Best Practices for Using ExpectedCondition in Selenium:

  1. Prefer Explicit Waits Over Thread.sleep(): Use WebDriverWait with ExpectedConditions to wait for specific events instead of fixed delays.
  2. Use the Right Condition for the Scenario: Choose conditions like visibilityOfElementLocated, elementToBeClickable, or titleContains based on what you’re testing.
  3. Set Reasonable Timeouts: Avoid overly long or short wait times. Balance stability with speed (e.g., 10–30 seconds depending on app behavior).
  4. Avoid Waiting for Elements Inside Loops: Move waits outside loops to prevent multiple redundant evaluations that can slow down execution.
  5. Handle Dynamic Elements: For elements that load or change often, use conditions like presenceOfElementLocated or stalenessOf.
  6. Combine Conditions if Needed: Use custom ExpectedCondition implementations or logical operators to wait for complex scenarios.
  7. Log Failures Clearly: Wrap waits with try-catch blocks and include meaningful logs to help debug wait failures.
  8. Avoid Overusing Fluent Waits Without Need: Use FluentWait only when you need polling intervals or exception ignoring—stick with WebDriverWait for most cases.
  9. Test for Disappearance When Needed: Use invisibilityOfElementLocated or stalenessOf when waiting for elements to disappear (e.g., loading spinners).
  10. Keep Waits Close to Action: Place waits just before interacting with dynamic elements to improve script reliability.

Why Run Selenium Tests on Real Devices?

Running Selenium tests on real devices ensures that your web application behaves as expected in real-world conditions. Emulators and simulators can’t fully replicate device-specific quirks, performance issues, or browser behaviors.

Real devices reveal layout shifts, rendering bugs, or touch responsiveness problems that often go unnoticed in virtual environments.

Key Benefits:

  • Accurate Rendering: Validate UI consistency across screen sizes, resolutions, and OS versions.
  • True Browser Behavior: Capture real-world issues like caching, cookies, and performance delays.
  • Touch and Gesture Testing: Ensure functionality works with real user interactions.
  • Improved Test Confidence: Reduce false positives and improve the reliability of your test results.

Use BrowserStack Automate to run Selenium tests on 3,500+ real devices and browsers without maintaining infrastructure. It enables fast, scalable testing directly integrated with your CI pipeline—so you can catch issues early and release with confidence.

Try Selenium Testing on Cloud

Conclusion

Including Selenium’s ExpectedConditions in explicit waits enhances test automation. These conditions offer fine-grained control over element states so that interactions only happen when elements are available. Such behavior lowers test flakiness and increases stability by eliminating timing-related failures.

Furthermore, explicit waits optimize the performance of tests by moving as soon as conditions are fulfilled, eliminating unnecessary wait times.

Generally, utilizing ExpectedConditions makes test scripts more stable, efficient, and maintainable, particularly when dealing with dynamic web pages.

Tags
Automation Testing Selenium Webdriver