Open In App

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Selenium WebDriver, managing the timing and availability of web elements is crucial for robust and reliable test automation. The waitForVisible and waitForElementPresent methods are traditionally used to ensure that elements are available for interaction on a webpage. However, in Selenium WebDriver with Java, these functionalities are effectively handled using the WebDriverWait class along with ExpectedConditions.

This article explores achieving equivalent results using these modern techniques, providing practical code examples to help you manage element visibility and presence in your tests.

Example

To demonstrate how to use WebDriverWait for waiting until an element is visible or present, we’ll create a simple example. In this scenario, we’ll automate a login process for the SauceDemo website, where we’ll wait for various elements such as input fields and buttons to become available before interacting with them.

Here’s a step-by-step breakdown of the code:

Setup the Project

First, include the necessary Selenium WebDriver and WebDriverManager dependencies in your project. If you’re using Maven, your pom.xml should include:

pom.xml

XML
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.6.0</version>
</dependency>
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.3.0</version>
</dependency>

Below is a complete example demonstrating the use of WebDriverWait to wait for elements to be visible or clickable before interacting with them.

WaitExample.java

Java
package com.example.tests;
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 io.github.bonigarcia.wdm.WebDriverManager;

import java.time.Duration;

public class WaitExample {
    public static void main(String[] args) {
        // Set up ChromeDriver using WebDriverManager
        WebDriverManager.chromedriver().setup();

        // Initialize ChromeDriver instance
        WebDriver driver = new ChromeDriver();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

        try {
            // Navigate to the SauceDemo homepage
            driver.get("https://www.saucedemo.com");
            
            // Pause to observe the process
            Thread.sleep(2000); // Sleep for 2 seconds

            // Wait for and interact with the username field
            WebElement usernameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("user-name")));
            usernameField.sendKeys("standard_user");

            // Pause to observe the typing
            Thread.sleep(2000); // Sleep for 2 seconds

            // Wait for and interact with the password field
            WebElement passwordField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("password")));
            passwordField.sendKeys("secret_sauce");

            // Pause to observe the typing
            Thread.sleep(2000); // Sleep for 2 seconds

            // Wait for and click the login button
            WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("login-button")));
            loginButton.click();

            // Pause to observe the click
            Thread.sleep(2000); // Sleep for 2 seconds

            // Wait for and verify the presence of the products title
            WebElement productsTitle = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("title")));
            if (productsTitle.isDisplayed()) {
                System.out.println("Login was successful and 'Products' page is visible.");
            } else {
                System.out.println("Login failed or 'Products' page is not visible.");
            }
        } catch (InterruptedException e) {
            System.err.println("Thread was interrupted: " + e.getMessage());
        } finally {
            // Ensure the browser is closed
            if (driver != null) {
                driver.quit();
            }
        }
    }
}

Output

  1. Opens the SauceDemo login page.
  2. Waits for the username and password fields to be visible, then inputs the credentials.
  3. Waits for the login button to be clickable, clicks it, and waits for the products page to load.
  4. Checks if the products title is visible, confirming a successful login.

You should see messages in the console indicating whether the login was successful and the products page is visible.

imresizer-1724634012750
Login window
WaitExample-Output
WaitExample Output

Conclusion

Using WebDriverWait with ExpectedConditions in Selenium WebDriver offers a powerful and flexible approach to handling element visibility and presence. This method allows you to wait until elements are interactable, reducing issues related to timing and synchronization. By applying these strategies, you can enhance the reliability of your Selenium WebDriver tests and ensure that your automation scripts perform consistently across different scenarios.


Next Article
Article Tags :

Similar Reads