Explicit Waits

Implicit waits work under the assumption that the element(s) we are searching for might take some time to appear on the DOM. Hence, an implicit wait will wait for every element that is part of our automation script.

On the other hand, explicit waits allow us to control the automation script flow for one or more specific elements, and under predefined conditions. The WebDriverWait and ExpectedConditions classes are used for setting explicit waits. The following lines set a 5-second explicit wait until the title of the page contains the string "Explicit". Note that if the title is updated before the 5-second waiting time, the automation script will continue to the next step:

WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.titleContains("Explicit"));

It is important to highlight that explicit waits act only on the elements involved in the wait process. Any other element won't be affected, and it is expected to be present when Selenium interacts with it. As a side note, explicit waits are also known as active waits.

Here are some of the pre-defined conditions supported by the ExpectedConditionsclass (http://seleniumhq.github.io/selenium/docs/api/java/index.html):

The following is an example of a Selenium test with an explicit wait:

public void explicitWaitExample() {
WebDriver driver = new ChromeDriver();
driver.get("https://trainingbypackt.github.io/Beginning-
Selenium/lesson_5/activity_5_B-1.html");

try {
/* Search for a button named runTestButton and click on it
to start the test*/
driver.findElement(By.id("runTestButton")).click();

// Set an explicit wait
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.titleContains("Explicit"));

// Verify expected changes
if (driver.getTitle().startsWith("Explicit")) {
System.out.println("ExplicitWait worked, the element
contains 'Explicit'");
} else {
System.out.println("Something went wrong with
ExplicitWait, 'Explicit' was not found");
}
} finally {
driver.quit();
}
}

We are now able to understand what an explicit wait is and how to implement one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.48.135