Timeouts Interface in WebDriver API

Introduction

Lets explore different types of waits in Timeouts Interface in WebDriver API in this article. In real scenarios testing web pages would be a challenge. Web pages take unpredictable time to load and page load times differ for every automation run. The test result might lead to false-negative when you don’t wait for a considerable amount of time and proceed further.

For example, let us say a web element took 5 sec to load and you waited only 3 sec in the test and reported no such element error and marked the test a failure!

Do not use Thread.sleep()

One bad practice used by Java automation testers to handle the condition is to introduce a sleep command ( Thread.sleep()). A hardcoded long sleep wait time makes tests slow and inaccurate. A well defined robust automation tool should be able to synchronize with the AUT.

Timeouts Interface

Timeouts Interface Selenium

 

Timeouts is an interface for managing timeout behavior for WebDriver instances. This interface has three methods that provide different wait strategies as shown in the picture.

implicitlyWait

An implicit wait specifies the amount of time the driver should wait when searching for an element if it is not immediately present. WebDriver polls the DOM(Document Object Model) for a certain amount of time when trying to find an element. The implicit wait is set for the life of the WebDriver driver instance. Increasing the implicit wait timeout should be used judiciously as it will have an adverse effect on test run time, especially when used with slower location strategies like XPath. This method might throw NoSuchElementException.

setScriptTimeout

JavascriptExecutor interface has two methods viz executeScript and executeAsyncScript. The executeScript method blocks the execution until the execution of the method is completed. On the other hand, executeAsyncScript is asynchronous and doesn’t block the execution. This method sets the amount of time to wait for an asynchronous javascript script to finish execution before throwing an error.

pageLoadTimeout

Sets the amount of time to wait for a page-load to complete before throwing an error. Note that if the timeout is negative, page loads can be indefinite. This method might throw TimeoutException.