What Is ExpectedConditions In Selenium With Examples

Himanshu Sheth

Posted On: April 14, 2021

view count117313 Views

Read time22 Min Read

The majority of the web products use AJAX (Asynchronous JavaScript and XML), due to which elements on the page are loaded at varying time intervals. This can lead to timing issues when automation testing is performed using the Selenium framework. What if a test is run on a WebElement that is not present in the DOM? The findElement function will raise ElementNotVisibleException.

Here are other scenarios that can cause issues in Selenium due to dynamic loading of elements:

  • WebElement (e.g. button) is visible but not clickable.
  • WebElement (e.g. label) is present in the DOM, but a certain text should be present in the element’s values attribute.
  • The title of the WebPage should consist of a case-sensitive substring and more.

The ideal way to overcome issues arising due to the dynamic loading of WebElements is by introducing Selenium waits in the test code implementation. Waits will provide the additional buffer-time required to complete the element’s loading and perform the necessary operation on the same. Rather than waiting for a specified time duration (also called Implicit Wait), wait is performed on a certain condition. These are called Expected Conditions in Selenium.

An explicit wait (for a maximum time duration) can be performed till a ‘certain condition’ (e.g. till the Element is not visible) is met. If the condition is not satisfied even after the max duration has elapsed, an appropriate exception is raised.

Being an automation test engineer, I have come across cases where explicit wait using Expected Conditions in Selenium has helped fix timing-related issues due to the dynamic loading of WebElements. In this Selenium tutorial, we look at how to use Expected Conditions in Selenium Java. If you are preparing for an interview you can learn more through Selenium interview questions.

ExpectedConditions In Selenium WebDriver

Expected Conditions provided by Selenium WebDriver are used for performing Explicit Waits on a certain condition. The Selenium WebDriver waits for the specified condition to occur before it can proceed further with the execution. This provides the required wait time between the actions that have to be performed, e.g. locating the WebElement or other valid operation with the element.

Explicit Wait With ExpectedConditions in Selenium

Implicit Wait involves Selenium WebDriver periodically polling the DOM for a set duration when a specific WebElement isn’t immediately accessible. Once configured, Implicit Wait remains active throughout the WebDriver object’s lifespan.

On the other hand, Explicit Wait using ExpectedConditions in Selenium lets you wait for the occurrence of a specified condition before execution can proceed to the next step. If the condition is not met within the expected time duration, an appropriate exception is raised.

In the above snippet demonstrating expected conditions in Selenium Java, the Selenium WebDriver waits for a maximum duration of 10 seconds until the WebElement with ID ‘dynamic element is found. The ExpectedCondition is invoked by the Selenium WebDriver every 500 ms until it returns success.

If the WebElement is available within 10 seconds (i.e. maximum wait duration), the ExpectedCondition returns true, and execution proceeds to the next step. A TimeoutException is thrown if the element is not present in the DOM even at the elapse of the maximum duration of 10 seconds.

Types of Expected Conditions In Selenium Java

Expected Conditions in Selenium WebDriver provide conditions that are frequently used for automating test scenarios for Selenium automation testing. Like other Selenium language bindings, Expected Conditions in Java provide ways through which you can realize Explicit Waits in the test code.

Here are the two major categories of ExpectedConditions in Selenium:

ExpectedCondition <WebElement>

As the name indicates, the locator of the WebElement is used as the parameter in the ExpectedCondition. Depending on the condition type, the explicit wait is performed until the expected condition is satisfied or the wait duration has elapsed.

If the expected condition is met, it returns the WebElement/list of WebElement/other information depending on the core implementation of the ExpectedCondition.

For example, the numberOfElementsToBeLessThan method in ExpectedConditions class (of org.openqa.selenium.support.ui.ExpectedConditions package) returns a List of WebElements if the number of WebElements located using the web locator (passed as the argument) is less than the expected number (also passed as an argument).

The elementToBeClickable method in Expected Conditions in Selenium Java returns a WebElement if the located element is clickable (i.e. it can be clicked). The appropriate Selenium locator for locating the WebElement is passed to the method.

ExpectedCondition <WebDriver>

This category of ExpectedCondition returns a WebDriver instance after the required operation is successfully performed.

For example, the frameToBeAvailableAndSwitchToIt method in Expected Conditions in Selenium Java switches the WebDriver to the specified frame that is located using the frameLocator (which is passed as the argument to the method). The frame can be located using the ID or Name web locators.

Read: Different Types of Locators in Selenium

An exception is raised if the given frame is not available to switch to.

selenium webdriver

ExpectedCondition <Boolean>

The condition of the type Boolean takes a String parameter, and the wait is applied to the condition of the parameter. On successful execution of the condition, the Boolean value true is returned, whereas false is returned if the condition is not met.

For example, the textToBePresentInElementLocated method returns true when the WebElement located by the web locator (which is passed as a parameter to the method) contains the specified text.

ExpectedCondition

ExpectedCondition <Alert>

This category of Expected Conditions in Selenium Java returns an alert if a window of type Alert is present on the page. Once the alert is present, the WebDriver switches to the Alert window. Post switching, various operations like Accept(), Dismiss(), sendKeys(), and getText() can be performed on the Alert Window.

Expected Conditions in Selenium Java

The method returns Null if the Alert window is not available within the specified wait duration.

Commonly Used ExpectedConditions In Selenium Java

Now that we have covered the different types (or categories) of Expected Conditions in Selenium Java, let’s have a look at some of the widely used ExpectedConditions for realizing Explicit Waits:

elementToBeSelected Method

elementToBeSelected is an overloaded method that belongs to the ExpectedCondition <Boolean> category.

Method Category – ExpectedCondition <Boolean>

ExpectedCondition<Boolean>elementToBeSelected(finalBy locator)

It lets the WebDriver wait until the WebElement is selected using the specified locator. This method of Expected Conditions in Selenium Java takes a single parameter ‘locator’ used for locating the required element.

It returns true once the element is selected, else it returns false.

Syntax

ExpectedCondition<Boolean>elementToBeSelected(final WebElement element)

The WebElement to be selected is passed as a parameter to the ‘elementToBeSelected ’ method. The elementToBeSelected method in turn calls the elementSelectionStateToBe method with the WebElement and Boolean value ‘true’ as the parameters to it.

elementToBeSelected

Syntax

elementToBeClickable Method

elementToBeSelected method of Expected Conditions in Selenium Java, is an overloaded method that belongs to the ExpectedCondition <WebElement> category. This method waits till the WebElement is visible and enabled so that the click operation can be performed on it.

Method Category – ExpectedCondition <WebElement>

Here is the brief of the elementToBeClickable​ method:

ExpectedCondition<WebElement>elementToBeClickable​(By locator)

The Selenium WebDriver waits till the element located using the specified web locator is visible and enabled so that the element can be clicked.

Syntax

ExpectedCondition<WebElement<elementToBeClickable​(WebElement element)

The Selenium WebDriver waits till the WebElement which is passed as the parameter is visible and enabled for it to be clicked.

Syntax

presenceOfElementLocated Method

This method waits for the specified WebElement to be present on the DOM of the page. The presence of an element does not necessarily mean that the particular element is visible.

The method takes the parameter – locator for finding the element on the page. It returns the WebElement once it is located.

Method Category – ExpectedCondition <WebElement>

Syntax

visibilityOfElementLocated Method

This method is used to check if the specified element is present in the DOM of the page, but it is also visible.

The method takes the parameter – locator for finding the element on the page. It returns the WebElement once it is located.

Method Category – ExpectedCondition <WebElement>

Syntax

titleIs Method

This method of Expected Conditions in Selenium Java checks whether the title of the current page matches with the expected title. It returns true if the title matches with the expected title.

It returns false if the titles do not match.

Method Category – ExpectedCondition <Boolean>

Syntax

titleContains Method

It checks whether the current page title or the title of a WebElement contains a particular substring in it. It returns true if the case-sensitive substring is present in the title.

Method Category – ExpectedCondition <Boolean>

Syntax

textToBePresentInElementLocated Method

This ExpectedCondition checks if the given text (passed as a parameter to the method) is present in the WebElement that matches the given web locator.

It returns the Boolean value true if the specified text is present in the element; else, it returns false.

Method Category – ExpectedCondition <Boolean>

Syntax

textToBePresentInElementLocated Method

This ExpectedCondition checks if the given text (passed as a parameter to the method) is present in the WebElement that matches the given web locator.

It returns the Boolean value true if the specified text is present in the element; else, it returns false.

Method Category – ExpectedCondition <Boolean>

Syntax

urlToBe Method

This ExpectedCondition checks whether the current page URL matches (or is the same as) the URL passed as a parameter to the urlToBe() method.

It returns true if the current page URL is the same as the expected URL (in the parameter); else, it returns false.

Method Category – ExpectedCondition <Boolean>

Syntax

frameToBeAvailableAndSwitchToIt Method

The frameToBeAvailableAndSwitchToIt method of Expected Conditions in Selenium Java is used for checking if the given frame is available to switch to. Frames in Selenium can be identified using any one of the following approaches:

  1. By locator
  2. Frame index (Integer)
  3. Frame name (String)
  4. WebElement (located using an appropriate web locator)

On those lines, the frameToBeAvailableAndSwitchToIt method is an overloaded method that provides the option to check for a given frame using the above-listed options for locating Frames (and iFrames) on a page.

If the said Frame (or iFrame) is present on the page, this method triggers a driver.switchTo().frame operation so that focus is shifted to the frame.

Method Category – ExpectedCondition<WebDriver>

Here are the details of the frameToBeAvailableAndSwitchToIt method:

ExpectedCondition<WebDriver>frameToBeAvailableAndSwitchToIt ​(By locator)

The ExpectedCondition checks whether the given frame is available to switch to. The required frame is located using the web locator passed to the method.

On successful execution, it switches the given driver to the specified frame; else, it returns null.

Syntax

ExpectedCondition<WebDriver>frameToBeAvailableAndSwitchToIt(int frameLocator)

It checks whether the given frame can be switched to. The frame on the page is located using the specified frameindex (or frameLocator), which is of Integer type.

Syntax

ExpectedCondition<WebDriver>frameToBeAvailableAndSwitchToIt ​(WebElement locator)

The frame to be switched to is located using the WebElement on which the findElement method is executed. On successful execution, it returns a WebDriver instance after switching to the frame is completed.

Syntax

ExpectedCondition<WebDriver>frameToBeAvailableAndSwitchToIt(String frameLocator)

The given frame is located using the Frame Name, which is passed as a parameter to the frameToBeAvailableAndSwitchToIt method.

If the frame with the specified name is present on the page, it switches the WebDriver to the specified frame. If the frame is not present, it returns null.

Syntax

alertIsPresent Method

As the name indicates, this ExpectedCondition instructs the command if an Alert window is available on the page. Based on the category of Alert Window (i.e. Simple Alert, Prompt Alert, Confirmation Alert), appropriate actions have to be performed on the window.

If the Alert window is present, this method internally triggers driver.switchTo().alert() so that the focus is on the Alert window.

alertIsPresent  Method

Method Category – ExpectedCondition <Alert>

Syntax

Examples : ExpectedConditions in Selenium Java

For demonstrating ExpectedConditions in Selenium Java, we create a TestNG project in IntelliJ named ExpectedCond. The project contains a package named org.expconditions which in turn consists of a class file named Test_ExpConditions.

ExpectedConditions in Selenium

The TestNG framework is used for creation and maintenance of test scenarios in Selenium automation testing. For the implementation, we use the Selenium 4 for Java language bindings. The dependency for Selenium 4 Java (Alpha-7) is downloaded from Maven central repository:

The testng.xml configuration file helps in organizing the tests. Shown below is the complete implementation of pom.xml and testng.xml.

All the tests are run on the cloud Selenium Grid by LambdaTest. To access the Selenium Grid, you should note the user name and access key from the LambdaTest profile page. The tests are executed on Chrome (latest version) + Windows 10 combination – capabilities are generated using the LambdaTest Capabilities Generator. All the tests are run on Selenium 4 Grid.

LambdaTest Capabilities Generator.

Since all the tests would be a part of the same file, the Remote WebDriver is instantiated in method [testSetUp()], which is implemented under the @BeforeClass annotation. A string array str_url contains the test URLs used for the tests mentioned in the subsequent sections. The WebDriver instance is freed once all the tests that demonstrate ExpectedConditions in Selenium are executed.

Here is the implementation of the methods under @BeforeClass and @AfterClass annotations.

Let’s look at all respective tests where we demonstrate a few of the widely-used ExpectedConditions in Selenium.

elementToBeClickable ExpectedCondition In Selenium Java

Test Scenario

  1. Go to https://phptravels.com/demo/
  2. Locate the “Google Play” button
  3. Wait for the button to be clickable
  4. Click on the button
  5. Assert if the page URL (that opens up due to click on Google Play Button) does not match with the expected URL

Implementation

Code Walkthrough

  1. Locate the “Get It On Google Play” button on https://phptravels.com/demo/.
  2. Perform a vertical scroll by 600 pixels using the “window.scroll” command provided by JavascriptExecutor.
  3. Create a WebDriverWait (or Explicit Wait) with a wait duration of 5 seconds.
    Since we are using selenium-java (4.0.0-alpha-7), WebDriver wait is created as below:
    Selenium 4 (for Java)

    If selenium-java (3.141.59) is used, wait (of 5 seconds) is created in the following manner:
    Selenium 3 (for Java)

    Since we are using Selenium 4 for Java, we have used the former approach for creating WebDriverWait (or Explicit Wait).

  4. The WebDriver does an Explicit Wait for 5 seconds until the requisite element is clickable (i.e. it can be clicked). If the element is not found, an exception is raised; else, the execution moves to the next step, where we click the button.

  5. Since the link (after the click) opens in a new window (or tab), we switch to the new window using its window handle.

  6. Assert if the current URL (in the new window) does not match with the expected URL.

Execution

As seen in the execution snapshot obtained from the Automation Dashboard on LambdaTest, the test was executed successfully.

alertIsPresent ExpectedCondition In Selenium Java

Test Scenario

  1. Go to http://the-internet.herokuapp.com/javascript_alerts.
  2. Locate the “Click for JS Alert” button.
  3. Click the button to invoke the alert window.
  4. Wait till the alert window is present.
  5. Accept the alert.

Implementation

Code Walkthrough

  1. Go to the test URL http://the-internet.herokuapp.com/javascript_alerts and locate the button ‘Click on JS Alert’ using the findElement method in Selenium. The element is located using the XPath property.

  2. Click on the button to invoke the Alert.

  3. Do an Explicit Wait of 5 seconds until the ExpectedCondition alertIsPresent is met (or satisfied).

  4. If the alert is not present, an exception is thrown; else, the WebDriver switches to the Alert window. Accept the alert using the accept() method.

Execution

As seen below, the alert window is present, and the test executes successfully.

test executes successfully

textToBePresentInElementLocated ExpectedCondition In Selenium Java

Test Scenario

  1. Go to http://the-internet.herokuapp.com/dynamic_content?with_content=static. The page contains dynamic content, i.e. content changes at every refresh.
  2. Go to the element (third text area) where the content dynamic is available.
  3. Check for the presence of the text “laudantium” in the text area specified in step(2). If the text is not found, refresh the page and again perform the search operation.
  4. Print the contents in the text area where the presence of the required text is detected.

Implementation

Code Walkthrough

  1. Go to the test URL. As seen below, the text in the marked areas changes on every page reloads, whereas content in the remaining areas of the page remains constant (or is static even after the page is refreshed).
  2. Create a variable of type “By” where we use the cssSelector property for locating the WebElement. Instead of the Inspect in Chrome, we made use of the POM Builder extension in Chrome to get the cssSelector of the required element.
  3. cssSelector

  4. Create an Explicit Wait (or WebDriverWait) of 5 seconds.
  5. In a While loop, the text in the element is compared with the expected text. If the text is not found (after a maximum duration of 5 seconds), a TimeoutException is thrown. In the catch (for TimeoutException), we increment the search counter and refresh the page using the navigate().refresh() method offered by Selenium.
  6. If the text is present, ExpectedCondition textToBePresentInElementLocated returns true.

    Here is the complete implementation of Step (4).

Execution

If the search term is not present in the required WebElement, an exception is thrown and the counter is incremented. As seen in the execution screenshot, the search term “laudantium” is located after 11 attempts.

visibilityOfElementLocated ExpectedCondition In Selenium Java

Test Scenario

  1. Go to https://phptravels.com/demo/.
  2. Locate the link (or element) with the title “Affiliate”.
  3. Perform a vertical scroll till the ExpectedCondition visibilityOfElementLocated returns a WebElement mentioned in Step(2).
  4. Click on the WebElement and assert if the current page title does not match the required title.

Implementation

Code Walkthrough

  1. On the test URL, create a variable of type ‘By’ and use the cssSelector property in it.
  2. Create an Explicit Wait of 5 seconds.
  3. In a while loop, perform a check if the ExpectedCondition visibilityOfElementLocated returns a valid WebElement. If the condition returns Null (i.e. the element is not present on the page or the Wait times out), perform a vertical scroll by 100 pixels and check for the presence of the required WebElement (i.e. Affiliate).
  4. Perform a click operation on the Selenium WebElement located using ExpectedConditions.visibilityOfElementLocated (element_locator).
  5. Assert if the title of the current page does not match with the expected title.

Execution

As shown below, the ‘affiliate link’ on the test URL is opened successfully.

frameToBeAvailableAndSwitchToIt ExpectedCondition In Selenium Java

Test Scenario

  1. Go to https://jqueryui.com/spinner/.
  2. Find the Elements with TagName “iframe” for checking the number of frames present on the web page.
  3. Perform a vertical scroll by 200 pixels till the intended frame is available.
  4. Switch to the intended frame using the ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame_locator) method.
  5. Click on a button which is located inside the frame.

Implementation

Code Walkthrough

  1. After navigating to the test URL https://jqueryui.com/spinner/, we find the total number of iFrames using findElements method with tagName ‘iframe’.
  2. Do a vertical scroll of 200 pixels using “window.scrollBy” with the executeScript method of JavascriptExecutor.
  3. Use WebDriverWait with a duration set to 5 seconds for creating an explicit wait.
  4. The By class is instantiated so that the WebElement can be located using the findElement method in Selenium.
  5. The required frame is located using the web locator declared in step (4), and the frameToBeAvailableAndSwitchToIt method of Expected Conditions in Selenium Java switches to the intended frame. If the frame is not present on the page, the method returns null.

  6. Click on the ‘setValue’ button, which is located inside the frame.
  7. The presenceOfElementLocated method of Expected Conditions in Selenium Java is used for detecting the presence of the WebElement with the web locator defined in step (6). The click operation is performed on the button.

Execution

The execution snapshot obtained from the Automation Dashboard indicates that the test was executed successfully.

elementToBeSelected ExpectedCondition In Selenium Java

Test Scenario

  1. Go to https://lambdatest.github.io/sample-todo-app/.
  2. Locate the elements with the names “li1” and “li2”.
  3. Click (or enable) the elements located in step (2).
  4. Wait until the elements – “li1” and “li2” are selected (or enabled).
  5. Wait till the element with the name “li3” is selected.
  6. The test is passed if a Timeout Exception is thrown for element “li3”.

Implementation

Code Walkthrough

  1. The findElement method in Selenium automation testing is used for locating the WebElements with the name “li1” and “li2”.

  2. The elements are “selected” (or enabled) using the click method.

  3. The elementToBeSelected method of Expected Conditions in Selenium Java is used for checking whether the elements “li1” and “li2” are selected. The maximum wait duration is set to 5 seconds.

  4. The elementToBeSelected method is used for the element with name “li3”. After 5 seconds (maximum wait duration), ExpectedCondtions results in a Timeout Exception.

Execution

As expected, the test results in a Timeout Exception for elements with name “li3”.

Run Selenium Java Test

Custom ExpectedConditions In Selenium

There are scenarios where you would want to combine multiple conditions into one and trigger the same in the test case. Consider a case where the test looks for the visibility of the element and post the visibility; it checks whether the element is clickable. This can be achieved by creating a custom ExpectedCondition’ in Selenium.

Custom ExpectedCondition is a class that:

  • Implements the ExpectedCondition Interface (e.g. ExpectedCondition<WebElement>, ExpectedCondition<Boolean>, etc.)
  • Has a constructor with parameters of the ExpectedCondition (Optional)
  • Overrides the apply method using the @Override annotation in Java

Here is a sample implementation of a custom ExpectedCondition in Selenium Java:

Let’s look at how to create custom ExpectedCondition in Selenium Java by automating the following test scenario:

Test Scenario

  1. Go to https://phptravels.com/demo/.
  2. Locate the link (or element) with the title “Affiliate”.
  3. Click on the WebElement and assert if the current page title and URL do not match the required title & URL.

Implementation

We created a new file named Test_customconditions under the package org.expconditions. This is how the project and testng.xml looks like when the new file is created:

Project Structure

Implementation

Code Walkthrough

  1. We first use a custom ExpectedCondition that checks whether the URL and page title are inline with what is expected in the test. The class TestURLLoaded implements ExpectedCondition<Boolean> and overrides the apply method.

    The apply method returns True if the Page title and Page URL are correct else it returns false.

    In the test code, we wait for a duration of 10 seconds on the custom condition implemented earlier.

    The WebDriver waits for a maximum of 10 seconds until (((boolean) wait.until(new TestURLLoaded(testURL, testURLTitle)) returns either true or false. If the custom ExpectedCondition returns false (i.e. exception is raised), it means that URL and Page title are not as expected in the test.

    A value of true means that we can proceed with the next step in the test scenario (i.e. locating the Affiliate link and clicking on the same).

  2. The class ElementLocated is a custom condition class that implements ExpectedCondition<WebElement> interface.

    In the apply method, we locate the WebElement (i.e. Affiliate link) using the cssSelector locator and return the same for usage in the test code.

    In the test case, a vertical scroll by 100 pixels is performed till the custom ExpectedCondition returns true (i.e. the required WebElement is located).

  3. Once the WebElement with affiliate link is located, we click on the same and use the custom ExpectedCondition (i.e. TestURLLoaded) that checks whether the page title and page URL of the affiliate page is as per the expectation. The custom condition is used in the wait.until() method with wait duration set to 10 seconds.

Execution

As seen in the execution snapshot obtained from the automation dashboard on LambdaTest, the affiliate link on the test page was located, and the click operation on the link was successful:

The Condition Was As Expected

Expected Conditions are used for realizing Explicit Waits in Selenium. It is advantageous compared to Implicit Wait, where the wait is performed for the entire ‘wait’ duration even if the WebElement was located much earlier than the total duration. ExpectedCondition <Boolean>, ExpectedCondition <WebDriver>, ExpectedCondition <WebElement>, and ExpectedCondition <Alert> are the four major categories of ExpectedConditions in Selenium Java.

Custom ExpectedConditions in Selenium automation testing are useful when you want to combine different conditions to achieve a specific task. Custom ExpectedCondition implements the ExpectedCondition interface and overrides the apply method. To summarize, explicit wait with ExpectedConditions have a huge upper hand over Implicit Waits and should be preferred wherever applicable in the test implementation.

Author Profile Author Profile Author Profile

Author’s Profile

Himanshu Sheth

Himanshu Sheth is a seasoned technologist and blogger with more than 15+ years of diverse working experience. He currently works as the 'Lead Developer Evangelist' and 'Senior Manager [Technical Content Marketing]' at LambdaTest. He is very active with the startup community in Bengaluru (and down South) and loves interacting with passionate founders on his personal blog (which he has been maintaining since last 15+ years).

Blogs: 132



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free