Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?
Last Updated :
05 Sep, 2024
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
- Opens the SauceDemo login page.
- Waits for the username and password fields to be visible, then inputs the credentials.
- Waits for the login button to be clickable, clicks it, and waits for the products page to load.
- 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.
Login window
WaitExample OutputConclusion
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.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Random Forest Algorithm in Machine Learning
A Random Forest is a collection of decision trees that work together to make predictions. In this article, we'll explain how the Random Forest algorithm works and how to use it. Understanding Intuition for Random Forest AlgorithmRandom Forest algorithm is a powerful tree learning technique in Machin
7 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
10 min read