top of page
Writer's pictureNeha Saini

Waits Commands in Selenium

Why Wait?

In today's world of automation testing, timing is everything. Imagine running a test script that goes through a web application, just to have it fail because the page didn't load fast enough, or an element wasn't visible right at that moment when the script tried to work with it. This could be because of several reasons like network speed, server response time, and many more. These are the types of timing issues that can make automated tests unreliable and frustrating for maintenance and a complete waste of time. This is where the concept of "WAITS" in automation testing becomes crucial.


What is Selenium Wait?

Selenium wait is a feature used in automation testing to make your script pause for a while until a specific condition is met, like a webpage element loading or becoming interactive. It's like telling Selenium to "wait until you're sure the thing you are looking for is ready."


There are three main types of waits in Selenium:

  1. Implicit Wait

  2. Explicit Wait

  3. Fluent Wait


Now let's see what Implicit Wait is.

Implicit wait is a type of Wait in Selenium which instructs the Web Driver to wait for a certain amount of time before throwing an exception if an element is not found. It is applied globally to each, and every element location calls for the entire session. If the implicit wait is set for 10 seconds, the Web Driver will wait for 10 second before throwing an error and during that duration as soon as the element is found it will return the elements reference.


Let's take a real-life example to understand more clearly:


Imagine you're at a vending machine trying to buy a snack. You press the button, but sometimes the snack takes a moment to drop. Instead of instantly assuming the machine is broken, you give it a bit of time (e.g., 10 seconds). If the snack falls within that time, you grab it and move on. If not, you decide the machine isn't working.


Implicit Wait Syntax:

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));


Components of the Code:


  • driver.manage(): Accesses the manage interface of the Web Driver, which provides methods to configure browser settings and timeouts.

  • timeouts(): Accesses the Timeouts interface, allowing you to set various types of waits (like implicit waits, page load timeouts, and script timeouts.

  • implicitlyWait(Duration.ofSeconds(10)):

* Sets the implicit wait duration to 10 seconds.

* Duration.ofSeconds(10) creates a Duration object representing 10 seconds, it was introduced in Java 8 as part of the java.time package.


How it works

  • After setting this wait, whenever a WebDriver command tries to locate an element, it will wait up to 10 seconds for the element to become available.

  • The wait applies globally to all findElement and findElements calls in the script, until it is overridden or reset.


Example:



When to Use Implicit Wait

  • Global Waiting for All Elements

    Use it when you want a default wait time applied to all elements in your script without setting individual conditions.

  • Handling Minor Loading Delays

    Ideal for webpages where elements take varying but predictable short durations to appear.

  • Less Precision Needed

    Best for straightforward test scenarios where exact conditions or complex waits are not required.

  • Static Loading Patterns

Effective if the webpage elements have a consistent loading behavior that doesn't required dynamic checks.


In summary, we can say that the line driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

configures WebDriver to wait for up to 10 seconds for elements to appear in the DOM before failing.



Explicit Wait

Explicit wait in Selenium is a mechanism that allows the WebDriver to wait for a specific condition to occur before proceeding with the next step in the code. Unlike Implicit waits, which apply globally, explicit waits are applied only to specific elements or conditions, making more flexible and precise.


Setting Explicit Wait is important in cases where there are certain elements that naturally take more time to load. If one sets an implicit wait command, then the browser will wait for the same time frame before loading every web Element. This causes an unnecessary delay in executing the test script.


Explicit wait is more intelligent but can only be applied for specified elements. However, it is an improvement on implicit wait since it allows the program to pause for dynamically loaded Ajax elements.


Explicit Wait Syntax:


WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30)); //Line 1

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("example"))); //Line 2


Code breakdown:


  • WebDriverWait :

    WebDriverWait is a class in Selenium that helps your program wait for a certain condition to happen before proceeding. In line1 WebDriverWait wait creates a variable named wait of type WebDriverWait. We can use this variable to define waiting conditions. (as in Line 2)

  •  new WebDriverWait(driver,Duration.ofSeconds(30)):

    This creates an instance of WebDriverWait with two parameters:

    driver: This is the browser instance controlled by selenium. It tells Selenium which browser to wait for.

    Duration.ofSeconds(30): Specifies the maximum wait time. In this code will wait up to 30 seconds for the specified condition to be met. If not, it throws an error.

  • wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("example"))): This tells Selenium to wait until an element with the ID "example" is visible, or up to 30 seconds. If the condition is met sooner, it proceeds right away.


Example:


In short, WebDriverWait helps your program handle the unpredictability of web applications by intelligently waiting for elements to be ready.



Fluent Wait

Fluent wait in Selenium marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the Exception.

To put it simply, Fluent Wait looks for a web element repeatedly at regular interval until timeout happens or until the object is found. Fluent wait commands are most useful when interacting with web elements that can take longer durations to load.

Fluent waits are also sometimes called smart waits because they dont wait out the entire duration defined in the code. Instead, the test continues to execute as soon as the element is detected.


Now let's take a real-life example to get a clear idea about fluent wait:


Imagine you're waiting for a delivery package at your doorstep:

  • You expect the package to arrive within 30 minutes.

  • Every 5 minutes, you check your doorstep to see if it has arrived.

  • If the package isn't there, you don't panic or complain (you just ignore this "error" and check again later).

Now, map this scenario to the Selenium code:

  • You can think of your package as Web element you're waiting for (e.g., a button or text field on a webpage).

  • And checking doorstep as Polling for the element's visibility.

  • Ignoring errors = Ignoring temporary issues, like "element not found" initially.


Fluent Wait Syntax:

Wait<WebDriver> wait = new FluentWait<>(driver) 

.withTimeout(Duration.ofSeconds(30)) // Maximum time to wait

 .pollingEvery(Duration.ofSeconds(5)) // Check condition every 5 seconds

 .ignoring(NoSuchElementException.class); // Ignore specific exceptions

// Use FluentWait to wait for a condition

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("example")));


Code breakdown:


  • Wait<WebDriver> wait = new FluentWait<>(driver):

This line sets up a FluentWait object in Selenium.

Wait<WebDriver>:

* Wait is an interface in Selenium that provides methods for waiting until certain conditions are met.

* <WebDriver> specifies the type of object this wait will act on, which in this case is a WebDriver instance (the browser driver controlling your browser).

new FluentWait<>(driver):

* new: Creates a new object.

* FluentWait: A class in Selenium that allows you to define custom waiting behavior.

  • .withTimeout(Duration.ofSeconds(30)):

    Sets the maximum wait time to 30 seconds. Selenium wait for the condition for up to 30 seconds.

    (Same as you'll wait for your package for 30 minutes before giving up.)

  • .pollingEvery(Duration.ofSeconds(5)):

    Specifies how often Selenium will check the condition. Here, it will check every 5 seconds.

    (Like in every 5 mins, you go to the door to see if the package has arrived. )

  • .ignoring(NoSuchElementException.class):

    Tells Selenium to ignore specific error during polling.


  • WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("example"))):

    This tells Selenium to:

    1. Wait until an element with the ID "example" becomes visible on the webpage.

    2. Stop waiting once the element appears and assign it to the element variable.

    3. If the element doesn't appear within 30 seconds, throw a timeout error.

    (Same as once the delivery person arrives and you see the package, you stop checking the door. If 30 minutes pass and no one comes, you give up.)


    Example:


    In summary, FluentWait is like waiting for a delivery package with a plan -- setting a maximum wait time, checking at regular intervals, and ignoring false alarms.


    Conclusion:

    Efficient use of waits in Selenium is key to creating reliable and robust test scripts. By understanding and applying implicit, explicit, and fluent waits appropriately, you can handle dynamic web elements effectively, minimize flaky tests, and improve test execution efficiency. Choose the right wait strategy based on your application's behavior for the best results.


17 views

Recent Posts

See All
bottom of page