Skip to main content

Selenium webdriver wait -Implicit wait & Explicit wait


While building test automation for a complex web application using Selenium WebDriver then we face some exception like NoSuchElementException ,ElementNotVisibleException etc.

Problem :-
when the application server or webserver is serving the page too slowly due to resource constraints like :-
  1. Slow Network
  2. Slow response from webserver
  3. Element visible after some time due to Ajax and Javascript.
  4. Webpage is not loaded properly
   etc.

Solution:-
where you have to calculate and configure the average wait time your test scripts should wait for WebElements to load on the webpage.We need to use one of the next two approaches: implicit or explicit waits.

There are three ways by which you can make WebDriver wait for WebElement:-
  1. Implicit wait
  2. Explicit wait
  3. Fluent wait
  1. Synchronizing test using implicit wait
Wait time is the time your driver will wait for the WebElement to load before it gives up and throws NoSuchElementException. Implicit wait time is used when you want to configure the WebDriver's wait time as a whole for the application under test.When an implicit wait is implemented in tests, if WebDriver cannot find an element in the Document Object Model (DOM), it will wait for a defined amount of time for the element to appear in the DOM.
Note :-When webdriver find any element then each time webdriver will wait for a defined amount of time element to visible. Implicit timeout is generic to all the WebElements of a web page.

WebDriver gives an option to set the implicit wait time for all of the operations that the driver does using the manage() method.

Syntax :- driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Lets understand this line of code :-
The Selenium WebDriver provides the Timeouts Interface for configuring the implicit wait. The Timeouts Interface provides an implicitlyWait() method, which accepts the time the driver should wait when searching for an element.


Example:-

  1. public class ImplicitWaitTime {
  2. public static void main(String... args) {
  3. WebDriver driver = new FirefoxDriver();
  4. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  5. driver.get("www.google.com");
  6. }
  7. }


     2. Synchronizing test using Explicit Wait

The Selenium WebDriver also provides an explicit wait for synchronizing tests, which provides a better control as compared with an implicit wait.

Problem :-
Implicit timeout is generic to all the WebElements of a web page But, if you have one specific WebElement in your application where you want to wait for a very long time, this approach may not work.

Solution:-
So you have to make an exception for only a particular case, like this WebElement. To handle such scenarios, WebDriver has explicit wait time for a WebElement . Explicit wait is an intelligent kind of wait, but it can be applied only for specified elements. Explicit wait gives better options than that of an implicit wait as it will wait for dynamically loaded Ajax elements
.
The Selenium WebDriver provides WebDriverWait and ExpectedCondition classes for implementing an explicit wait
The ExpectedCondition class provides a set of predefined conditions to wait before proceeding further in the code.

The following are the Expected Conditions method that can be used in Explicit Wait:-
  1. alertIsPresent()
  2. elementSelectionStateToBe()
  3. elementToBeClickable()
  4. elementToBeSelected()
  5. frameToBeAvaliableAndSwitchToIt()
  6. invisibilityOfTheElementLocated()
  7. invisibilityOfElementWithText()
  8. presenceOfAllElementsLocatedBy()
  9. presenceOfElementLocated()
  10. textToBePresentInElement()
  11. textToBePresentInElementLocated()
  12. textToBePresentInElementValue()
  13. titleIs()
  14. titleContains()
  15. visibilityOf()
  16. visibilityOfAllElements()
  17. visibilityOfAllElementsLocatedBy()
  18. visibilityOfElementLocated()

Example:-

public void testExplcitWaitTitleContains()
{
//Go to the Google Home Page
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
//Enter a term to search and submit
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("selenium");
query.click();
//Create Wait using WebDriverWait.
//This will wait for 10 seconds for timeout before title is
//updated with search term
//If title is updated in specified time limit test will move to
//the text step
//instead of waiting for 10 seconds
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.titleContains("selenium"));
//Verify Title
assertTrue(driver.getTitle().toLowerCase().
startsWith("selenium"));
driver.quit();
}



3.  FluentWait

Fleunt wait is an smart kind of wait, the fluent wait is used to tell 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.

FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.

There are some points were we can use Fluent wait:-

  1. Frequency: Setting up a repeat cycle with the time frame to verify/check the condition at the regular interval of time     Exmaple:-suppose you want to check element in some frequency then we can achieve by using fluent wait
  2. Whenever we want to ignore some exceptions during running script then we can achieve by using Fluent wait.
     etc.


Syntax:-

// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
1. Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                                             .withTimeout(30, TimeUnit.SECONDS) .
                                             .pollingEvery(5, TimeUnit.SECONDS) 
                                            .ignoring(NoSuchElementException.class);

2.WebElement foo = wait.until(new Function<WebDriver, WebElement>()
3.{
4.public WebElement apply(WebDriver driver)
5.{
6.return driver.findElement(By.id("foo"));
7.}
8.}
9.);


Code explanation:-

Line 1: Create Fluent wait instance
Line 2: In Fluent wait class there are some methods we use these methods here like:

  1. withTimeout(long duration, java.util.concurrent.TimeUnit unit) method is used to Sets how long to wait for the evaluated condition to be true.
  2. pollingEvery(long duration, java.util.concurrent.TimeUnit unit) method is used to Sets how often the condition should be evaluated.In short we set frequency.
  3. ignoring(java.lang.Class<? extends java.lang.Throwable> exceptionType) method is used to ignore Expections

Comments

Popular posts from this blog

Appium architecture (How Appium works internally)

Appium Architecture  A ppium is a cross-platform automation tool, API of it supports both OS (Android and iOS) test scripts.It is tested on simulators (iOS,), emulators (Android), and real devices (iOS, Android)   Appium is an HTTP server written in Node.js that creates and handles WebDriver sessions.The Appium web server follows the same approach as the Selenium WebDriver, which receives HTTP requests from client libraries through JSON and then handles those requests in different ways   JSON wire protocol The JSON wire protocol  ( JSONWP ) is a transport mechanism created by WebDriver developers. This wire protocol is a specific set of predefined, standardized endpoints exposed via a RESTful API.   Appium implements the Mobile JSONWP, the extension to the Selenium JSONWP, and it controls the different mobile device behaviors, such as installing/uninstalling apps over the session Let’s have a look at some of the endpoints from the API whi...

Handle radio button & Check Boxes in Selenium

The main difference between Radio button and Checkbox is that, using radio button we will be able to select only one option from the options available. whereas using checkbox, we can select multiple options. Selenium WebDriver supports Radio Button and Radio Group controls using the WebElement class. We can select and deselect the radio buttons using the click() method of the WebElement class and check whether a radio button is selected or deselected using the isSelected() method. Before performing the click on the Radio buttons or check boxes we will have to verify follwing scenarios :- If Radio button or Checkbox is displayed on the webpage If Radio button or Checkbox is enabled on the webpage Check the default selection of the Radio button or Checkbox We use predefined methods present in selenium to handle check Box and Radio  button :- isDisplayed() isEnabled() isSelected() 1.  isDisplayed () this method returns a Boolean value, i...

Read data from Properties file in Selenium

Java properties file is used to store project configuration data or settings. In this blog, we will show you how to read and write to/from a properties file. In this blog we are going to read username and password from properties file(.config)  Step 1 :- Create config.properties file in Java project  Navigate to File menu -> New -> Click on File Step 2:- Write some data in config.properties file Step 3 :- Create Java class to read properties file  Example how preform login using properties file in Seleniuim  : import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class ReadProper  {   public static Properties prop;   public static void mai...