Mastering the use of Wait commands is crucial for becoming an expert in Selenium WebDriver and creating a robust test automation framework.
It is important to handle dynamic web elements by using proper wait mechanisms. These commands are vital for executing test scripts effectively and addressing issues related to delays in web elements.
Overview
What is WaitUntilVisible in Selenium?
WaitUntilVisible in Selenium is an explicit wait condition that pauses execution until a specified web element becomes visible. It helps handle dynamically loaded elements, preventing errors like NoSuchElementException and improving test stability.
Why Use WaitUntilVisible in Selenium?
- Handles Dynamic Elements: Ensures elements that load asynchronously are visible before interaction.
- Prevents Errors: Avoids NoSuchElementException and ElementNotInteractableException.
- Enhances Test Stability: Reduces flakiness caused by varying load times.
- Improves Automation Reliability: Ensures UI elements are ready for interaction, leading to consistent test execution.
- Optimizes Execution: Eliminates unnecessary delays by waiting only as long as needed.
Understanding Dynamic Web Elements
Dynamic web elements are elements on a web page that change their attributes (such as class or id), appearance, content, or behaviour during the runtime of a webpage or test execution.
Various reasons may trigger this dynamic nature of web elements, such as user interactions, DOM refresh or page reload, AJAX requests or server-side actions, JavaScript, etc.
Read More: Selenium WebElement Commands
Challenges in handling Dynamic Web Elements
Handling dynamic web elements can be a challenging task for web automation testers as the state of the element may keep changing while interacting with them.
Dynamic elements do not have static locators, which can cause tests to fail occasionally, produce inaccurate test results, and undermine the reliability of the test scripts. Some of the major challenges with dynamic web elements are listed below:
- Change in Element’s State: If the state of the element changes during the test execution, Selenium may not be able to interact with the element as it would not be accessible and may throw NoSuchElementException or StaleElementReferenceException.
- Delay in Element Load: Web elements that are dynamically loaded via JavaScript or AJAX calls are not loaded instantly on the webpage, which may lead to TimeoutException or StaleElementReferenceException errors.
- Element’s State and Visibility: Web elements may be disabled or hidden for some time or may not be visible due to a modal pop-up blocking their view or any other UI behaviour. Selenium may fail to locate such elements when it tries to interact with them.
- Slow Network: Slow network conditions can delay the loading of dynamic web elements, resulting in Selenium TimeoutExceptions.
Read More: findElement and findElements in Selenium
What is WaitUntilVisible in Selenium?
WaitUntilVisible is a Selenium concept where explicit waits are used to wait until a specific web element becomes visible on the web page before interacting with it.
Web automation testers often face difficulty when dealing with dynamic web elements, as they may not be immediately visible for interaction due to a delay in page load, JavaScript executions, or any other factor.
Selenium provides a way to wait for elements until they meet certain conditions (like being clickable or visible) using explicit waits.
WebDriverWait class and ExpectedConditions, are used to implement the “wait until visible” mechanism.
Why use WaitUntilVisible in Selenium?
Here are the top reasons why you must use WaitUntilVisible in Selenium:
1. Handles Dynamic Elements
Many web applications have elements that load asynchronously due to JavaScript execution, AJAX calls, or delayed rendering.
Using WaitUntilVisible, Selenium waits until the element appears in the DOM and is visible before proceeding, preventing interaction with non-existent elements.
2. Prevents Errors
Without explicit waits, Selenium might attempt to interact with an element that hasn’t appeared yet, leading to exceptions like:
- NoSuchElementException (element not found in the DOM)
- ElementNotInteractableException (element is in the DOM but not visible)
- StaleElementReferenceException (element reloaded before interaction)
3. Enhances Test Stability
Web pages may load at different speeds depending on network conditions, server response times, and browser behaviors.
WaitUntilVisible ensures that the automation script does not fail due to inconsistent element load times, reducing test flakiness.
4. Improves Automation Reliability
Ensuring that elements are visible before interaction guarantees that test steps execute as expected.
This prevents false negatives in test reports and improves confidence in automation test results.
5. Optimizes Execution
Instead of using inefficient fixed sleep (time.sleep()), which unnecessarily delays execution, explicit waits only pause for as long as needed.
This speeds up test runs while ensuring elements are ready for interaction, improving overall efficiency.
Read More: Understanding Selenium Timeouts
Types of Waits in Selenium
In Selenium, Waits are crucial for making the test scripts stable, reliable, and robust, mainly when working with dynamic web elements that may not render correctly or may take some time to load.
1. Implicit Wait: When trying to find an element, implicit wait tells the WebDriver to poll the
DOM (Document Object Model) for a certain amount of time before throwing an exception. It applies globally to all the elements in the test and by default the time is set to 0.
Once set, the implicit wait is set for the life of the WebDriver object. Implicit wait and explicit wait should not be used together as it may lead to unpredictable behaviour.
Example: In the below Selenium code, implicit wait of 10 seconds is applied to all the web elements on the web page.
public class Timeouts { WebDriver driver; @Test public void implicitWait() { driver=new ChromeDriver(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); driver.get("https://www.browserstack.com"); driver.findElement(By.cssSelector("a#signupModalProductButton")).click(); driver.quit(); } }
2. Explicit Wait: Explicit wait tells the WebDriver to wait for a specific condition to occur before executing the next test steps. With explicit waits, you define a specific conditio,n such as the visibility of an element or its ability to be clicked. Post this, the WebDriver will wait for this condition to be true before performing the action.
Example: In the below Selenium code, an explicit wait of 10 seconds is applied to the “Get Started Free” button before clicking on it.
import java.time.Duration; 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 org.testng.annotations.Test; public class Timeouts { WebDriver driver; @Test public void explicitWait() { driver=new ChromeDriver(); driver.get("https://www.browserstack.com"); WebDriverWait wait=new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element=wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a#signupModalProductButton"))); element.click(); driver.quit(); } }
3. Fluent Wait: Fluent wait is a more specialized and flexible waiting mechanism which allows you to define polling intervals, the exceptions to ignore, and maximum time duration.
In simple words, a fluent wait looks for a web element repeatedly at regular intervals until the timeout happens or the web element is found.
Example: In the below Selenium code, the Fluent Wait is applied to the “Get Started free” button. It will check every 2 seconds to see if the element is clickable and will wait up to 10 seconds. It will also ignore any exceptions during this waiting period.
import java.time.Duration; 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.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.testng.annotations.Test; public class Timeouts { WebDriver driver; @Test public void fluentWait() { driver=new ChromeDriver(); driver.get("https://www.browserstack.com"); Wait<WebDriver> wait= new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(10)) .pollingEvery(Duration.ofSeconds(2)) .ignoring(Exception.class); WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a#signupModalProductButton"))); element.click(); driver.quit(); } }
Handling Dynamic Web Elements using WaitUntilVisible in Selenium
It is essential to handle dynamic web elements with automation test scripts that load the web page and web elements asynchronously.
WaitUntilVisible mechanism helps to ensure that the web element is present and visible before performing any action on it.
You can handle dynamic elements using WebDriverWait class along with ExpectedConditions.visibilityOf method which waits until the element is visible.
The Selenium code below will provide a more detailed understanding:
import java.time.Duration; 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 org.testng.annotations.Test; public class Timeouts { WebDriver driver; @Test public void implicitWait() { driver=new ChromeDriver(); driver.get("https://www.browserstack.com"); WebDriverWait wait=new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a#signupModalProductButton"))); element.click(); driver.quit(); } }
Best Practices for using WaitUntilVisible in Selenium
Follow these best practices when using WaitUntilVisible in Selenium:
1. Do not mix Implicit Wait and Explicit Wait: Implicit wait is applied globally, and explicit wait is applied locally to a specific element. Using both the waits together in any automation framework can lead to unpredictable and random behavior. It is always recommended to choose any one wait and use it throughout the framework.
2. Avoid Thread.sleep(): Avoid Thread.sleep() as it enforces fixed wait times ,which could be unnecessarily long if the element becomes available before the specified duration.
3. Use ExpectedConditions Appropriately: ExpectedConditions class provides various methods to wait for specific conditions such as clickability, presence, visibility, etc. Using the right condition is important for maximum performance.
For example, use elementToBeClickable when you want the element to be clickable on the web page, use presenceOfElementLocated when you want the element to be present in the DOM, but visibility is not required, use visibilityOfElementLocated when you want the element to be visible on the web page.
4. Implement retry logic for flaky tests: To handle flaky tests, it is always a good practice to implement retry logic. Retry a few times to find the web element which is not immediately available on the web page before marking the test as a failure.
int maxRetryCount = 3; for (int retry = 0; retry < maxRetryCount; retry++) { try { // Interact with the element break; // Exit loop on success } catch (Exception e) { // Log the exception or retry message } Thread.sleep(2000); }
5. Handle timeouts gracefully: Occasionally, elements may not be available even after applying proper wait time, and if they are not handled properly, they may fail the tests unexpectedly.
It is always recommended to wrap the wait.until conditions in a try-catch block to handle timeouts gracefully. Implement appropriate action such as logging, taking a screenshot, or printing meaningful error messages in the catch block.
try { WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)) .until(ExpectedConditions.visibilityOfElementLocated(By.id("submit_button"))); element.click(); } catch (TimeoutException e) { System.out.println("Element not visible within the given time"); }
Why choose BrowserStack to run Selenium Tests?
BrowserStack Automate simplifies Selenium testing by offering cross browser testing and cross-platform support, real-device testing, and the ability to run tests at scale in a cloud-based environment.
Here are the reasons why you must choose BrowserStack to run Selenium tests:
- Parallel Testing: Parallel testing is paramount in reducing overall execution time as it lets the testers execute the scripts simultaneously on multiple devices/ browsers.
- Real devices and browsers: Testing on emulators and simulators can be easy, however it may not give accurate test results at all times with respect to functional and even non-functional testing such as application’s performance. With BrowserStack, you can easily access all the latest devices without needing to purchase them.
- Dedicated Dashboard: Automate provides a dashboard to monitor and manage your tests. It displays test results (Pass/Fail/Pending), device and browser details, test duration, screenshots, and more.
- Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for automated test execution. With this feature, it allows to customize the structure and content of the report as per user’s need
- Easy Integration with CI/CD Pipeline: Automate can be easily integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI. The team can achieve faster delivery cycles with great confidence in the reliability, performance and compatibility of the application across different devices and platforms.
Conclusion
Mastering Selenium Wait commands is essential for testers to create efficient test automation frameworks. Effective and appropriate use of waits can simplify selenium automation testing processes.
However, for the outcomes of these commands to be genuine every time, they must be run on real browsers and devices instead of emulators or simulators to replicate real-time user experience.
BrowserStack provides access to 3500+ devices, browsers, and operating systems to test your applications across different environments without needing to maintain complex infrastructure.