top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Selenium Wait Functions

What are Wait Commands?

Waits are nothing but commands in selenium that are very important while executing the test scripts. During automated testing of websites, issues may occur due to variation in time lag for

loading web elements. Wait commands help to troubleshoot the issues.


Why use Wait Commands?

Waits are characteristic features of any UI test for dynamic applications. They synchronize of AUT and test script. An application response to commands is much slower than script performance. Wait commands direct a test script to pause a certain time before throwing a ElementNotVisibleException. That’s why in scripts wait time is essential so the application can interact with it. They help them less flaky and more reliable. Selenium provides multiple waits to make element visible or pause your script execution based on few scenarios.


Types of Selenium Waits:

· Implicit Wait

· Explicit Wait

· Fluent Wait


Implicit Wait

The Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it throws a “No Such Element Exception”. The default setting is 0. Once we set the time, the web driver will wait for the element for that time before throwing an exception.

To add Implicit Wait in test script, import the following package by giving.

Import java. util. concurrent. TimeUnit;

Syntax for Implicit wait

driver. manage (). timouts (). implicitlyWait (20, TimeUnit.SECONDS) ;


Examples of Implicit Wait

Add the above syntax in test scripts.


import java. util. concurrent. TimeUnit;

import org. openqa. selenium. By;

import org. openqa. selenium. Webdriver

import org. openqa. selenium.chrome.ChromeDriver;

import org. testng. annotations. Test;


public class VerifyTitle


{

@Test


public void verifySeleniumTitle ()


{

WebDriverManager.chromedriver().setup();


WebDriver driver=new ChromeDriver ();

// Specify implicit wait of 20 seconds

driver. manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);

                    String ExpectedTitle = “NumpyNinja”;
                    String ActualTitle=””;
              // Base URL                               
               driver.get ("https://dsportalapp.herokuapp.com/login");
                        //To maximize the browser

driver. manage (). window (). maximize();

              //Compare the actual title with the expected title
                  ActualTitle = driver.getTitle();
                  if (ActualTitle.equals(ExpectedTitle))
                  {
                    System.out.println( "Title matches");
                   }
                   else {
                  System.out.println( "Title  fail to match" );

}

}

}

Consider the above implicit wait syntax which will accept 2 parameters, the first parameter will accept the time as an integer value and the second parameter will accept the time measurement in terms of Seconds,Milliseconds,Nanoseconds,Days,Hours.


Explicit Wait


Explicit waits are used to halt the execution until a particular condition is met or the maximum time has elapsed. If the condition is not met within the specified timeout value, then an exception is thrown. Unlike Implicit waits, Explicit waits are applied for a particular instance only.

Syntax for Explicit Wait


WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(15) );

WebElement element= wait.until(ExpectedConditions.elementToBeClickable(By.id(“element_id”)));


By default, it calls the expected result every 500 milliseconds but in this case it tries up to 15 seconds(mentioned in syntax value as 15) before throwing an exception. A successful return value will be a Boolean(True or False) or non-null object.


Examples of Explicit Wait


import java. util. concurrent. TimeUnit;

import org. openqa. selenium. By;

import org. openqa. selenium. Webdriver

import org. openqa. selenium.chrome.ChromeDriver;

import org. testng. annotations. Test;



public class VerifyTitle


{

@Test

public void verifySelenium()

{

WebDriverManager.chromedriver().setup();

WebDriver driver=new ChromeDriver ();

          //To maximize the browser

driver. manage (). window (). maximize();

// Base URL

       driver.get ("https://dsportalapp.herokuapp.com/login");
       //specify explicit wait 

WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(15) );

driver.findElement(By.xpath(“//button[@class=’btn’]”));

String ExpectedTitle = “NumpyNinja”;

String ActualTitle=””;

ActualTitle = driver.getTitle();

    //compare the actual title with the expected title
             if (ActualTitle.equals(ExpectedTitle))
                {
                    System.out.println( "Title matches");
                  }
             else {
                   System.out.println( "Title  fail to match" );
                   }

WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“//div//nav/a”));

}

}

The above code states that we are waiting for an element for the time frame of 20 seconds as defined in the “WebDriverWait” class on the webpage until the “ExpectedCondition” are met and the condition is “visibilityofElementLocated“.


Mainly used some examples of ExpectedCondition predefined methods are,

· elementToBeClickable (Bylocator) – An expectation for checking an element is visible and enabled such that you can click it.

· elementToBeSelected (WebElementelement)- An expectation for checking if the given element is selected.

· presenceOfElementLocated (Bylocator) – An expectation for checking that an element is present on the DOM of a page.

· urlToBe (java.lang.String url) – An expectation for the URL of the current page to be a specific url.

· visibilityOf (WebElementelement) - An expectation for checking that an element, known to be present on the DOM of a page, is visible.



Fluent Wait


The Fluent Wait in Selenium is used to define maximum time for the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an “ElementNotVisibleException” exception. It checks for the web element at regular intervals until the object is found or timeout happens. This wait is similar to explicit wait and also similar to terms of functions and management. Can perform wait for action for an element only when we know the exact time to click or visibility of an element. It is also known as smart primarily because they don’t want to wait for the maximum time out. We can specifically mention the time it needs to wait to perform the action.

Let us see how the fluent wait works in several methods to configure the wait condition


withTimeout()


This method is used to set the maximum time to wait for the condition to occur, if condition doesn’t occur within the timeframe then exceptional error would occur.


pollingEvery()


It is used to set the frequency to check the condition ,if condition is not met script will wait for the specified time.


Ignoring()


This method is used to ignore the exceptions during the wait like no such exception can be ignored once it found an element.



Syntax for fluent wait


Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class) ;


Examples of Fluent Wait

public class VerifyTitle

{

@Test

public void verifySeleniumTitle ()


{

WebDriverManager.chromedriver().setup();


WebDriver driver=new ChromeDriver ();

     //To maximize the browser

driver. manage (). window (). maximize();


//Fluent time for 5 seconds


Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class);


    // Base URL
       driver.get("https://dsportalapp.herokuapp.com");  
        String ExpectedTitle = “NumpyNinja” ;
        String ActualTitle=”” ;
        ActualTitle = driver.getTitle();
       //compare the actual title with the expected title
         if (ActualTitle.equals(ExpectedTitle))
             {
            System.out.println( "Title matches");
              }
         else {
             System.out.println( "Title  fail to match" );

}}

}


Conclusion


In conclusion to these waits are much important in selenium that allows you to synchronize your test scripts with the dynamic web applications. Using waits you can wait for a specific condition to occur before performing the next action by ensuring our test scripts run smoothly and accurately. Importantly have to know the exact wait time to make element clickable or visible instead of throwing an exception. Selenium wait plays a vital role by keeping test scripts to improve reliability and accuracy of your test automation.




71 views0 comments
bottom of page