Open In App

Expected Conditions in Selenium with Types and Examples

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

ExpectedConditions in Selenium are a powerful feature used to enhance the efficiency and reliability of test scripts. They help wait for specific conditions to be met before proceeding with further actions, ensuring that elements are present, visible, or in a specific state. By utilizing ExpectedConditions in Selenium WebDriver, testers can avoid common issues like stale elements or timing-related failures.

This approach results in more robust and resilient automation scripts, capable of handling dynamic web applications. The use of ExpectedConditions ensures that tests run smoothly and reduce the chances of false negatives, providing accurate results.

What are the conditions in Selenium WebDriver?

ExpectedConditions, in Selenium WebDriver, refers to a set of conditions that are somewhat like waitFor... functions that are used to synchronize the program’s test flow with the readiness of a Web element for interaction. These conditions assist in the management of dynamic content and help act, provided that the elements pass the defined criteria. ExpectedConditions allow testers to wait for visibility, for an element to be present, or for it to be clickable before attempting to act on it, and this decreases the variance of tests. Provided by the WebDriverWait class of WebDriver, ExpectedConditions assist in dealing with cases when elements are loaded dynamically or it takes time to make them clickable, so some frequent timing-related problems in automated testing are avoided.

Types of Expectedconditions

In Selenium WebDriver, ExpectedConditions are used for waiting when an element is in a particular state for taking an action. Here are some common types:

  • Visibility: replaceText: replaces text in an element.
  • Presence: presenceOfElementLocated: Waits for an element to be present in the DOM even if it is not visible.
  • Clickability: elementToBeClickable: Waits until the element is visible and can be interacted with, i.e., is clickable.
  • Text Presence: textToBePresentInElement: Waits until a text is specified within an element.
  • Attribute to be Present: attributeToBe is a stimulus that waits for an element to have a specific attribute that has a certain value.
  • Staleness: stalenessOf Waits until an element is no longer attached to the DOM.

Example of Selenium Expectedconditions

Here’s a practical example of using Selenium’s ExpectedConditions with WebDriverWait:

Java
package org.openqa.selenium.htmlunit;

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;

import java.time.Duration;

public class SeleniumExpectedConditionsExample {
    public static void main(String[] args) {
        // Set up the WebDriver (e.g., Chrome)
        WebDriver driver = new ChromeDriver();

        try {
            // Navigate to a webpage
            driver.get("https://example.com");

            // Create a WebDriverWait instance with a timeout of 10 seconds
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

            // Wait until the element with ID 'myElement' is visible
            WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("myElement")));
            
            // Perform actions on the element
            element.click();

            // Wait until the element with ID 'submitButton' is clickable
            WebElement submitButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("submitButton")));
            submitButton.click();

        } finally {
            // Clean up
            driver.quit();
        }
    }
}
Python
# code
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver
print("GFG")

# Set up the WebDriver (e.g., Chrome)
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get("https://example.com")

try:
    # Wait until the element with ID 'myElement' is visible
    element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.ID, 'myElement'))
    )
    # Perform actions on the element
    element.click()

    # Wait until the element with ID 'submitButton' is clickable
    submit_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, 'submitButton'))
    )
    submit_button.click()

finally:
    # Clean up
    driver.quit()

In this example:

  • visibility_of_element_located ensures that the element with ID 'myElement' is visible before attempting to click it.
  • element_to_be_clickable waits until the element with ID 'submitButton' is both visible and enabled before clicking it.

Custom Expectedcondition in Selenium

In Selenium, you can create custom ExpectedCondition classes to handle specific scenarios that aren't covered by the built-in conditions. Here’s how you can define and use a custom ExpectedCondition:

Example of a Custom ExpectedCondition

Suppose you want to wait until an element's text matches a specific value. Here’s how you can create a custom condition for that:

1. Define the Custom ExpectedCondition

Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TextToBeExactlyPresentInElement implements ExpectedCondition<WebElement> {
    private final By locator;
    private final String text;

    public TextToBeExactlyPresentInElement(By locator, String text) {
        this.locator = locator;
        this.text = text;
    }

    @Override
    public WebElement apply(WebDriver driver) {
        WebElement element = ExpectedConditions.presenceOfElementLocated(locator).apply(driver);
        return element != null && element.getText().equals(text) ? element : null;
    }

    public static void main(String[] args) {
        // Sample usage with WebDriver (assuming driver is already initialized)
        WebDriver driver = ...;  // Initialize WebDriver
        WebDriverWait wait = new WebDriverWait(driver, 10);
        
        By locator = By.id("sampleElementId");
        String expectedText = "Expected Text";

        TextToBeExactlyPresentInElement condition = new TextToBeExactlyPresentInElement(locator, expectedText);
        WebElement element = wait.until(condition);

        if (element != null) {
            System.out.println("Text is exactly present in the element.");
        } else {
            System.out.println("Text is not exactly present in the element.");
        }
    }
}
Python
from selenium.webdriver.support.expected_conditions import _find_element
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class textToBeExactlyPresentInElement:
    def __init__(self, locator, text):
        self.locator = locator
        self.text = text

    def __call__(self, driver):
        element = _find_element(driver, self.locator)
        return element if element.text == self.text else None

2. Use the Custom ExpectedCondition

Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

# Set up the WebDriver (e.g., Chrome)
driver = webdriver.Chrome()

# Navigate to a webpage
driver.get("https://example.com")

try:
    # Wait until the text of the element with ID 'myElement' is exactly 'Expected Text'
    WebDriverWait(driver, 10).until(
        textToBeExactlyPresentInElement((By.ID, 'myElement'), 'Expected Text')
    )
    print("Text is as expected.")

finally:
    # Clean up
    driver.quit()

Explanation

  • Custom Condition Class: textToBeExactlyPresentInElement is defined with __init__ to take a locator and the expected text. The __call__ method makes the instance callable and performs the actual check.
  • Usage: In the WebDriverWait, you use this custom condition to wait until the text of the element matches the expected value.

Advantages of Selenium Expectedconditions

Selenium's use of expected conditions has a number of benefits

  • Stability Boosted: By waiting for elements to reach a desired state before taking any action, they aid in the management of dynamic content. As a result, problems caused by elements not being accessible or interactable are less likely to arise.
  • Enhanced Dependability: Tests become more reliable and less prone to timing-related errors when conditions like visibility and clickability are explicitly defined, resulting in more consistent results.
  • Diminished Flakiness: ExpectedConditions assist with alleviating flakiness in tests brought about by timing issues or changes in page load times, as they trust that particular circumstances will be met before continuing.
  • Improved Coding: They give a cleaner and more comprehensible method for taking care of dynamic substances instead of utilizing hard-coded delays (rest), which can be less proficient and harder to keep up with.
  • Customizable: Selenium makes it possible to create one-of-a-kind expected conditions, giving you the flexibility to deal with unusual or difficult situations that may not be covered by the built-in conditions.
  • Problem Solving: Expected Conditions can be used to check the state of elements before interacting with them, allowing for more graceful error detection and handling by waiting for specific conditions.
  • Increased Efficiency: Utilizing ExpectedConditions maintains a strategic distance from superfluous holding up by promptly continuing once the condition is met, possibly working on the presentation of tests compared with fixed delays.

Conclusion

In conclusion, ExpectedConditions in Selenium are essential for creating effective and reliable test scripts. By leveraging these conditions, you ensure that your tests wait for specific elements or states before proceeding, which helps to manage dynamic content and avoid common issues like timing errors and stale elements. Utilizing ExpectedConditions enhances the stability of your automated tests, making them more accurate and resilient. This approach leads to more dependable test results and improves the overall quality of your test automation efforts.


Next Article
Article Tags :

Similar Reads