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
How to do session handling in Selenium Webdriver using Java? In Selenium WebDriver, managing browser sessions is crucial for ensuring that each test runs independently and without interference. A browser session in Selenium is identified by a unique session ID, which helps track and manage the session throughout the test. Proper session handling in Selenium W
4 min read
How to ask the Selenium-WebDriver to wait for few seconds in Java? An open-source framework that is used for automating or testing web applications is known as Selenium. There are some circumstances when the particular component takes some time to load or we want a particular webpage to be opened for much more duration, in that case, we ask the Selenium web driver
9 min read
How to check that the element is clickable or not in Java Selenium WebDriver? Ensuring that an element is clickable in your Selenium WebDriver tests is crucial for validating the functionality and user experience of your web applications. In Java Selenium WebDriver, checking if an element is clickable before interacting with it can help avoid errors and ensure that your test
3 min read
How to Take a Screenshot in Selenium WebDriver Using Java? Selenium WebDriver is a collection of open-source APIs used to automate a web application's testing. To capture a screenshot in Selenium, one must utilize the Takes Screenshot method. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used t
3 min read
How to get text from the alert box in java Selenium Webdriver? In Automation testing, we can capture the text from the alert message in Selenium WebDriver with the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the WebDriver focus from the main page to the alert
2 min read
Send keys without specifying element in java Selenium webdriver Selenium webdriver gives us the power to interact with the web elements by locating the specific web element on the web page and performing intended actions on it. The Sendkeys method is one of the common methods that lets you send some keyboard inputs to specific web elements. However, it is not th
3 min read