Selenium Wait: Implicit, Explicit & Fluent Wait Commands

Vijay Kumar Kaushik

Posted On: March 4, 2024

view count165942 Views

Read time15 Min Read

Becoming proficient in automation testing with Selenium involves acquiring a strong grasp of effectively utilizing Selenium’s wait commands. These commands are crucial for testing automation as they ensure synchronized interaction with web elements, enabling the accurate execution of test scripts across various loading times and dynamic page changes.

This article will dive into Selenium waits and explain how testers use Selenium’s wait feature. We will cover all the Selenium waits – Implicit Waits, Explicit Waits, and Fluent Waits. We also break down the differences between implicit and explicit waits and explain when using each type of wait is best.

Why Do We Need Selenium Waits?

The primary challenge in test automation is ensuring the application is appropriately configured to execute a specific Selenium command as intended. One of the most common issues with test automation is race conditions. In a race condition, either the browser reaches the right state first (which results in the desired functionality), or the Selenium code gets executed first (which leads to unintended results). This race condition is one of the main reasons test results are unreliable.

The reason for such race conditions depends on many aspects, like network speed, content size, and the frontend technology/framework used. For Instance, Javascript frameworks like React or Angular take some time to load the different objects on the web page due to the dynamic update to the Document Object Model (also known as DOM).

Without an appropriate wait mechanism, automation tests tend to produce consistent results. The lack of stable and reliable test executions increases developer frustration and time spent debugging, ultimately reducing their productivity. To solve this problem, Selenium Waits comes to the rescue.

Can We Use Thread.sleep()?

Thread.sleep() is a Java construct that stops the program’s execution for a specified period. By using this, we can achieve the wait required to have reliable automation test scripts, but it comes with some challenges that discourage its use as follows:

  • Make Test Scripts Inefficient – Invocation of Thread.sleep() method waits for the specified period irrespective of any situation. This static behavior leads to unnecessary delays in executing the test scripts. Regardless of the load time of the elements while testing, the script will wait for a static duration and increase the test execution time.
  • Requires Explicit addition after every Selenium Command – While adding waits in the test scripts using Thread.sleep(), it requires adding it all the places, even though there is a requirement of a constant wait before accessing any element of the web page. This makes the test scripts difficult to maintain with time.
  • Sleep Duration Calculation – Determining the correct values for the sleep duration would become an essential and challenging task for every Selenium command.

Given these challenges, there are better solutions than using Thread.sleep(). Now, let’s look at Selenium waits, their different types, and how they address specific timing challenges in web automation.

What are Selenium Waits?

Selenium Waits is a test automation concept defined as three commands — Implicit Waits, Explicit Waits, and Fluent Waits, that facilitate synchronization between script actions and dynamic web elements.

These waits introduce pauses during test execution, allowing the script to wait until specific conditions are met. Rather than a mere pause, Selenium waits are intelligent as they adapt to the varying loading times of web pages. This ensures that automated tests remain robust and unaffected by potential element visibility or availability delays. As a result of Selenium waits, automation scripts in dynamic web environments are more reliable and stable.

Types of Selenium Wait Commands

Selenium provides three primary types of wait commands to handle different timing scenarios and enhance the reliability of the automated tests as follows:

  • Implicit Wait – Implicit Wait in Selenium is a global wait that applies to all elements in the script. It sets a maximum wait time for any element to become available before interaction. If the element appears within the specified time, the script continues; otherwise, it raises a TimeoutException.
  • Explicit Wait – Explicit Wait in Selenium is a more granular approach that allows you to wait for a specific condition or element. Explicit waits are applied to individual elements and provide better control and precision. It often uses the WebDriverWait class and expected conditions to define custom waiting criteria. Explicit waits are useful for efficiently handling dynamic web elements with different load times.
  • Fluent Wait – Fluent Wait in Selenium allows one to wait for a specific condition to be met with a custom frequency of checking the condition. Fluent waits are particularly useful when dealing with elements that may take varying times to load or change state. This wait is created using the FluentWait class and configured with options like timeout, polling frequency, and exceptions to ignore.

Implicit Wait In Selenium

In Selenium, an implicit wait is a mechanism instructing the WebDriver to wait for a certain period before throwing an exception. It is applied globally to the entire script, and its primary purpose is to wait for elements to be present in the DOM (Document Object Model) before performing actions on them.

When an implicit wait is set, the WebDriver will repeatedly poll the DOM for a specified duration until the element is found or the timeout period expires. If the element is found within the specified time, the WebDriver proceeds with the next step in the script. An exception is thrown if the element is not found during the implicit wait period.

By default, the value for implicit wait is set to zero, which means that if the element is not found, it will immediately return an error. To enable the Implicit Wait In Java, the following syntax is used on the web driver object.

Setting Implicit Waits early in the script immediately after initializing the WebDriver. This establishes a uniform waiting period for all subsequent interactions.

Explicit Wait In Selenium

Explicit wait in Selenium is a technique where the WebDriver is directed to wait for a certain condition to be met before proceeding with the execution of the next steps in the script. Unlike implicit wait, which is applied globally and waits a specified amount of time for elements to appear, explicit wait focuses on specific conditions for individual elements.

With explicit wait, wait for certain conditions such as an element’s presence, an element’s visibility, or a specific attribute can be configured for an element to be in a particular state before proceeding further. The explicit wait command is implemented using the Selenium WebDriverWait class in Java.

Below is the code snippet to understand how Explicit Wait can be configured and used.

Types of Expected Conditions

Explicit waits provide a way to wait for certain conditions to be met before executing the test script or raising exceptions for not being able to meet that condition. This is done with the help of Selenium’s ExpectedConditions class. Multiple conditions can be used for waits as follows:

  • Element Visibility: The visibilityOfElementLocated() condition ensures that an element is present in the DOM and visible on the page.
  • Element Clickability: The elementToBeClickable() condition is crucial for scenarios where an element needs interaction, such as clicking a button.
  • Text to Be Present In Element: The textToBePresentInElementLocated() condition ensures that the text is present in a specified element.
  • Presence of Elements: The presenceOfElementLocated() condition waits for at least one element to be present in the DOM.
  • The invisibility of Elements: The invisibilityOfElementLocated() condition waits for the specified element to be invisible.
  • Frame to Be Available and Switch To It: The frameToBeAvailableAndSwitchToIt() condition waits for the specified frame to be available and switches to it.
  • Alert to Be Present: The alertIsPresent() condition waits for an alert to be present and switches to it.
  • Element Selection State: The elementSelectionStateToBe() condition waits for an element to be in a particular state, either selected or unselected.
  • Staleness of Element: The stalenessOf() condition waits for an element to become stale, indicating that it is no longer attached to the DOM.
  • Custom Conditions with ExpectedConditions: The attributeToBe() condition waits for the definition of custom conditions. For instance, waiting for an element to have a specific attribute value.

You can explore the official Selenium Java documentation of the ExpectedConditions class to learn more.

Fluent Wait In Selenium

In Selenium, Fluent wait provides a more flexible way of waiting for certain conditions to be met before proceeding with the execution of the script. It implements the Wait interface and allows you to define the polling frequency and exceptions to ignore during the waiting period.

The fluent wait command is implemented using the Selenium FluentWait class in Java. The key feature of FluentWait is its “fluent” or chainable syntax, where you can apply different conditions and configurations in a chain.

As shown here in this code snippet, while instantiating the object for the Wait, we can mention the wait duration, polling duration, and the exception that this wait can ignore. Post instantiation of fluent wait, it can be used while accessing a web element by passing in a Function in the until method of wait.

Comparing Selenium Waits: Explicit, Implicit, and Fluent Waits

Picking the right waiting strategy in Selenium matters for smooth automation. Let’s compare Implicit, Explicit, and Fluent Waits to make it understandable.

Characteristic Implicit Wait Explicit Wait Fluent Wait
Scope Affects all elements across the website universally. Can be applied individually to specific elements. Allows for personalized waiting strategies tailored to specific elements.
Complex Conditions Supported Best suited for basic checks on whether an element is present or not. Supports a variety of conditions, like visibility or clickability, through explicit Conditions. Offers a high level of flexibility by accommodating user-defined specific conditions.
Configuration Set globally once for a consistent application throughout the entire website. Configurable independently for different elements, providing nuanced control. Resembles Explicit Wait but introduces additional configurations for heightened precision.
Use case Well-suited for straightforward scenarios with consistent loading times. Ideal for tackling complex situations, especially when the loading behavior is unpredictable. Effective in dynamic scenarios marked by changes and variable loading times.
Wait Time Configuration Globally set, ensuring a uniform waiting time across the entire site. Can be configured individually for specific elements or scenarios, allowing for granular control. Customizable on a per-element basis, enabling tailored waiting times.
Polling Interval Config Operates with a fixed default interval of 500ms between checks. Permits users to set the frequency of condition checks, defaulting to 500ms intervals. Adheres to the same polling interval configuration as Explicit Wait.
Ignoring Exceptions Lacks the ability to selectively ignore exceptions. Allows for selective suppression of specific errors during the waiting period. Aligns with Explicit Wait in terms of exception handling.
Flexibility Relatively straightforward with limited customization options. Offers enhanced adaptability, accommodating various waiting scenarios. Highly adaptable, particularly beneficial for specific and nuanced situations.
Readability and Express Basic in nature due to its global application, providing less detailed insights. Exhibits greater expressiveness, especially when employing diverse Conditions. Demonstrates high expressiveness with a fluent API, contributing to code clarity.
Info Note

Automate your tests on a Selenium based cloud Grid of 3000+ real browsers and devices.Try LambdaTest Today!

Common Mistakes to Avoid While Using Selenium Waits

Exploring Selenium waits is essential, but avoiding common mistakes is equally important. Some pitfalls to avoid while using Selenium waits:

  • Excessive Reliance on Implicit Waits: Relying solely on Implicit Waits may lead to synchronization issues. Supplement them with Explicit or Fluent Waits for better adaptability in dynamic web scenarios.
  • Inadequate Wait Times: Avoid script failures by setting reasonable wait times. Elements may take longer to load; patience in allocating wait durations enhances the robustness of your tests.
  • Overlooking ExpectedConditions: Leverage the power of ExpectedConditions with Explicit and Fluent Waits. Neglecting these conditions might result in less adaptable and robust scripts.
  • Ignoring StaleElementReferenceException: Handle StaleElementReferenceException with care, which raises when an element is no longer attached to the DOM but a reference to the element is still being used. Ignoring it can lead to failures when interacting with stale elements. Use Explicit Waits judiciously to address this issue.
  • Poor Exception Handling: Wisely manage exception handling in Fluent Waits. Neglecting it may overlook crucial errors, affecting script reliability. Ensure effective debugging with meticulous exception management.
  • Neglecting Dynamic Conditions: Adapt your waits to the dynamic nature of web pages. Neglecting this may result in brittle scripts prone to failure. Selenium waits shine in dynamic scenarios.
  • Forgetting to Reset Implicit Waits: After modifying the Implicit Wait globally, remember to reset it. Forgetting to do so can impact other parts of your script, and maintaining consistency is crucial.
  • Inconsistent Wait Strategies: Maintain a consistent wait strategy throughout your test suite. A mix of Implicit, Explicit, and Fluent Waits may cause confusion and script instability. Strive for consistency.
  • Not Utilizing WebDriverWait Methods: Leverage the methods provided by WebDriverWait for efficient wait handling. Neglecting them may result in verbose and less readable code. Optimize your script with WebDriverWait’s capabilities.

Conclusion

Becoming a Selenium WebDriver expert demands mastering Selenium Waits—a vital skill ensuring precise test script execution and mitigating timing issues. In our exploration, we’ve uncovered the necessity of Selenium Waits in the asynchronous realm of web pages, where inconsistent element loading prevails. While Thread.sleep() offers a static solution, Selenium Waits dynamically adapts, optimizing script execution in varying load times.

We delved into key Selenium Waits—Implicit, Explicit, and Fluent—each tailored for specific scenarios. Implicit Wait, with global applicability, suits consistent load times. Explicit Wait provides element-specific precision, ideal for dynamic pages. Fluent Wait is highly adaptable and expressive and excels in unpredictable environments.

Our journey highlighted common mistakes to avoid, emphasizing the need for a balanced approach. In conclusion, Selenium Waits are indispensable for effective web automation, offering the precision required for seamless and reliable test scripts.

Frequently Asked Questions (FAQs)

Why do we need Selenium Waits in web automation?

Selenium Waits ensure synchronization between script actions and dynamic web elements, accommodating variations in page loading times.

Can Thread.sleep() be a suitable alternative to Selenium Waits?

While possible, Thread.sleep() introduces inefficiencies and static behavior, making it less favorable for dynamic web environments.

What are the key differences between Implicit, Explicit, and Fluent Waits in Selenium?

Each wait type caters to specific scenarios—Implicit for global waits, Explicit for element precision, and Fluent for adaptability in dynamic environments.

Should we use implicit and explicit waits together in Selenium automation?

It is generally not recommended to use implicit and explicit waits together due to potential conflicts and unpredictable behavior. These two types of waits serve similar purposes and combining them may lead to redundant or conflicting timeouts.

What is the significance of ExpectedConditions in Explicit Waits?

ExpectedConditions provide a range of conditions (visibility, clickability, etc.) for Explicit Waits, enhancing script adaptability.

How does Fluent Wait offer more flexibility in Selenium automation?

Fluent Wait allows developers to define custom polling intervals, ignore specific exceptions, and set up complex conditions for waiting on elements.

Can a mix of Implicit, Explicit, and Fluent Waits be used in the same test suite?

While possible, maintaining a consistent wait strategy throughout the test suite is recommended to ensure clarity and stability.

Author Profile Author Profile Author Profile

Author’s Profile

Vijay Kumar Kaushik

This is Vijay Kaushik, a Software Engineer keen to solve challenging software programming problems. Proficient in programming languages like Java, Python, Go, and Javascript. Have a great fascination for working with cloud technologies like Kubernetes and Istio. In my current role, I am responsible for End-to-end product delivery. Would love to work on products that push for Efficient Design with a secure and scalable system.

Blogs: 4



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free