ExplicitWait
As per the documentation, an ExplicitWait is a code block you define, configure and implement for the WebDriver instance to wait for a certain condition to be met before proceeding for the next line of code. There are some methods that helps us to implement ExplicitWait that will wait only as long as required. WebDriverWait in combination with ExpectedConditions is one of the way ExplicitWait can be achieved.
An Example
driver.get("http://www.example.com/");
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("element_css"))).click();
Explanation
This implementation of ExplicitWait waits up to 10 seconds before throwing a TimeoutException or if it finds the element then it will return within 0
to 10
seconds. WebDriverWait by default calls the ExpectedCondition every 500
milliseconds until it returns successfully. A successful return value for the ExpectedCondition function type is a Boolean
value of true or a not-null object.
Expected Conditions
There are some frequently encountered conditions when automating Web Browsers for testing Web/Mobile applications. The Java, C# and Python bindings include those convenient methods so we don’t have to write-up an ExpectedCondition class ourselves or create our own utility package for them. Some of the Expected Conditions are:
alertIsPresent()
elementToBeClickable(locator)
elementToBeSelected(WebElement)
frameToBeAvailableAndSwitchToIt(locator)
invisibilityOf(element)
Here you can find about the all the methods supported by Expected Conditions.
Inducing ExplicitWait
To induce ExplicitWait
, first you have to remove all the calls to implicitlyWait()
in your Test Framework
. Start a fresh execution and observe where you face the exception for an element attribute. The exceptions we will be facing will be either one of the follows:
NoSuchElementException
ElementNotVisibleException
ElementNotSelectableException
Now, we need to confirm the particular attribute of the WebElement for which we need to wait. If the WebElement in consideration is to be clicked we will consider Expected Conditions as elementToBeClickable(locator)
.
Element is Clickable implies Element is Displayed and Enabled.
Outro
Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.