Understanding ExpectedConditions in Selenium (with Types and Examples)

Related Product On This Page What is Expectedconditions in Selenium WebDriver?April 03, 2026 · 9 min read · Tool Comparison

Related Product

Understanding ExpectedConditions in Selenium (with Types and Examples)

When automating web application with to load properly is crucial.Expected Conditions in Seleniumprovide a reliable way to wait for specific states, like element profile, clickability, or alert, ensuring test 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 component is visible and enabled.
  • presence_of_element_located: Waits for the presence of an component in the DOM.
  • text_to_be_present_in_element: Waits until specific text look in a given element.
  • alert_is_present: Waits for an alert dialog to look.
  • element_to_be_selected: Waits until an component (like a checkbox) is selected.
  • invisibility_of_element_located: Waits until the element is no longer visible or present.

This article will explainExpectedconditionscommonly used in with examples.

What is Expectedconditions in Selenium WebDriver?

allows for waiting for specific conditions until a defined task is complete. An example is automating the task to check if all ingredient represent on a web page, matching a special, are seeable.

Syntax:

static ExpectedCondition & lt; WebElement & gt; visibilityOfElementLocated (By locator)

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

Read more:

Types of Expectedconditions

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

ExpectedCondition & lt; WebElement & gt;

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

ExpectedCondition & lt; Boolean & gt;

This stipulation has a twine parameter, and the delay 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 applies to the expect status, the condition code may render various elision.

Have a look at a few of the expected conditions:

1. static ExpectedCondition & lt; WebElement & gt; elementToBeClickable (By locater)

This condition is used to instruct a command to wait until the element is clickable by the locater.

2. static ExpectedCondition & lt; Boolean & gt; elementToBeSelected (By locator)

This condition instructs a bid to wait until the locator selects the ingredient.

3. electrostatic ExpectedCondition & lt; WebElement & gt; presenceOfElementLocated (By locater)

This condition instructs a command to wait until the component becomes visible or present.

4. static ExpectedCondition & lt; Boolean & gt; titleContains (String title)

This condition is used to instruct a bidding to check if the title of the web element or the webpage check the specific String or the group of characters.

5. unchanging ExpectedCondition & lt; Boolean & gt; titleIs (String rubric)

This precondition is used to instruct a dictation to ascertain whether the title is the String or the group of characters.

6.static ExpectedCondition & lt; Boolean & gt; urlToBe (String url)

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

This condition is used to instruct a command to ensure if the URL of the webpage matches the expected URL.

7. static ExpectedCondition & lt; WebElement & gt; visibilityOfElementLocated (By locator)

This status apprize a command to look until the element go seeable.

To learn about this in outstanding detail, concern to thisofficial sourceon ExpectedConditions

Also Read:

Example of Selenium Expectedconditions

The next example applies Expectedconditions to the Facebook login page.

import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; importee org.openqa.selenium.WebDriver; signification 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 course ExpectedCondtionsExample {public static void independent (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 (ingredient)); element.sendKeys (value);} //clickable method declared explicitly public unchanging void clickOn (WebDriver driver1, WebElement factor, int timeout) {new WebDriverWait (driver1, timeout) .until (ExpectedConditions.elementToBeClickable (element)); // Expectedcondition for the element to be clickable element.click ();}}

The codification has use Facebook sign-up credentials and located them. It has also created a generic function to create it available for all constituent to provide Explicit wait. The code apply Expected Conditions for the visibility of Element. The driver will look for 20 seconds to find if the element is visible. Then, using the, 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; signification org.openqa.selenium.support.ui.WebDriverWait;

Now, interpret how to make a Custom Expectedcondition in Selenium.

Read More:

Commonly Used Methods With ExpectedConditions

These method frequently help synchronise exam with web page behaviour:

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

Talk to an Expert

Custom Expectedcondition in Selenium

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

The following example will demo how to make 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))) cast 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 & amp; & amp; isUrlCorrect;}}

Executing the above codification, it will verify whether the abode page URL and the result page URL lucifer. Selenium will likewise check whether both URLs are display and wait until the page is loaded.

ExpectedCondition that can be apply in Explicit Waits

Explicit waits leveragingExpectedConditionsto hesitate test executing until a specified stipulation is met. Some additional utilitarian conditions include:

  • numberOfWindowsToBe (int expectedNumberOfWindows):Waits until the browser opens the expected number of window or tabs.
  • refreshed (ExpectedCondition & lt; T & gt; condition):Reapplies a condition after refreshing an element, utile to plow stale mention.
  • urlToBe (String url) / urlContains (String fraction):Waits for exact or partial URL lucifer, confirming pilotage 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 citation.

Read More:

Advantages of Selenium Expectedconditions

Selenium & # 8217; s ExpectedConditions grade, when hold with explicit waits, has multiple benefits that make the machine-controlled tests more authentic and effective.

  • Improved Performance:By waiting for sure conditions (e.g., visibleness, clickability), tryout are less prostrate 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 derogate unnecessary waiting time over fixed waits.
  • Exact Control Over Wait Conditions:Testers can specify specific conditions to wait for, like element visibleness or page title, providing greater control over test running.
  • Less Flakiness:Waiting for element to turn in a sure state before dealing with them assists in the shunning of errors such as ElementNotVisibleException, leave to more reliable examination outcomes.
  • More Transparent Test Intentions:Employing explicit waits with specified conditions clarifies the design of the test, enhance code readability and maintainability.
  • Improved Dealing with Dynamic Content:Explicit waits are useful in position where elements asynchronously load, for instance, with AJAX or JavaScript, so prove wait for element to be available before they interact.

Better Practices for utilise ExpectedCondition in Selenium

Here are Good Practices for UsingExpectedConditionin Selenium:

  1. Prefer Explicit Waits Over Thread.sleep (): Use WebDriverWait with ExpectedConditionsto wait for specific event instead of fixed wait.
  2. Use the Right Condition for the Scenario:Choose conditions likevisibilityOfElementLocated, elementToBeClickable, or titleContainsbased on what you & # 8217; re testing.
  3. Set Reasonable Timeouts:Avoid overly long or little wait clip. Balance stability with speed (e.g., 10–30 second bet on app behavior).
  4. Avoid Waiting for Elements Inside Loops:Move delay outside intertwine to keep multiple excess evaluation that can slow down performance.
  5. Handle Dynamic Elements:For elements that load or change often, use conditions likepresenceOfElementLocated or stalenessOf.
  6. Combine Conditions if Needed:Use usanceExpectedConditionimplementation or logical operators to wait for complex scenarios.
  7. Log Failures Clearly:Wrap waits with try-catch blocks and include meaningful log to help debug wait failure.
  8. Avoid Overusing Fluent Waits Without Need: Use FluentWaitonly when you need polling intervals or exception ignoring—stick withWebDriverWaitfor most cases.
  9. Test for Disappearance When Needed: Use invisibilityOfElementLocated or stalenessOfwhen waiting for elements to disappear (e.g., loading spinners).
  10. Keep Waits Close to Action:Place waits but before interacting with active elements to improve script reliability.

Read More:

Why Run Selenium Tests on Real Devices?

Running Selenium trial on existent devices ensures that your web application behaves as expected in real-world weather. can & # 8217; t fully replicate device-specific quirks, performance issues, or browser behaviors.

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

Key Benefits:

  • Precise Rendering:Validate UI eubstance across screen sizing, resolve, and OS versions.
  • True Browser Behavior:Capture real-world issues like hoard, cookies, and performance delay.
  • Touch and Gesture Testing:Ensure functionality works with real user interaction.
  • Improved Test Confidence:Reduce false positive and improve the reliability of your test termination.

Use to run Selenium tests on 3,500+ existent devices and browser without maintaining infrastructure. It enables fast, scalable testing straightaway integrated with your CI pipeline—so you can get issue early and freeing with confidence.

Conclusion

Including Selenium & # 8217; sExpectedConditionsin explicit waits enhances test automation. These weather offer fine-grained control over element states so that interactions only happen when elements are available. Such behavior lower screen flakiness and increases stableness by eliminating timing-related failure.

Furthermore, explicit postponement optimize the execution of tests by go as presently as conditions are fulfilled, eliminate unnecessary wait multiplication.

Generally, utilizingExpectedConditionsmakes test script more stable, efficient, and maintainable, particularly when address with dynamic web pages.

Tags
57,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free