Saturday, May 11, 2013

Wait in Selenium WebDriver

There are many types of waits in selenium WebDriver.
  1. Thread.sleep()
  2. Implicit Wait
  3. WebDriver Wait
  4. Wait for the Ajax call
  5. Wait for the page to load
1. Thread.sleep()

Here we can't predict the exact required wait time. With this we may need to wait for some extra seconds which decreases performances. These extra seconds became more when we execute multiple tests which increases the overhead. This wait is not recommended and we should not use this in our test.

2. Implicit Wait

This is the wait provided by WebDriver which is used, in general, for waiting for an element. This is recommended and we can use it. For example,
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
When we use this statement, the WebDriver waits for the element(on which next action is performed) till 30 seconds if that is not available immediately. After the timeout period, if the element is not available, it throws NoSuchElementException.
Use of this at the beginning of each test is very profitable and a best practice.
3. WebDriver Wait

This wait waits for a condition. This is also recommended and we can use it. This checks the condition in every 500 milliseconds until it returns true or the timeout. For example,
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
Here the condition is "ExpectedConditions.presenceOfElementLocated(By.xpath(xpath))" and this condition is checked in every 500 milliseconds until it is timed out by the timeout specified in timeOutInSeconds.

WebDriver wait is an explicit wait. You can refer here for more about implicit and explicit waits.


4. Wait for the AJAX call to complete

This is also recommended and very useful when we need to wait for some elements on the web page which is updating upon ajax calls.
You can refer the my post "Wait For Ajax call" for how to use this.

5. Wait for page to load

This is also recommended and very useful when you need to wait for a web page to load completely.
You can refer the my post "Wait for Page to load" for how to use this.

No comments:

Post a Comment