Implicit Waits

In Chapter 4, Advanced Element Location, we learned about how to find elements in the DOM (Document Object Model). But what if one or more elements cannot be found because they have not yet been loaded on to the page? That's when implicit waits are
helpful.

The TimeOuts interface provides the implicitlyWait method, which is necessary to set an implicit wait. This method receives two parameters (the waiting time and the time unit):

driver.manage().timeouts().implicitlyWait(5, the TimeUnit.
SECONDS);

Once an implicit wait is set, Selenium will wait up to 5 seconds (according to our preceding example) every time there is a call to the findElement method and the element was not found. During this wait, Selenium will poll to check if the element is already present, and if so, the element will be returned. Note that all of this is done at the server side, so the client has no control at all over the polling intervals; the client will just wait blindly for a response:

driver.findElement(By.id("runTestButton")).click();
WebElement info = driver.findElement(By.id("info"))

If the element is found, the automation script will continue, and the wait time will be set to zero (0). If the element cannot be found within the established 5 seconds, an exception will be thrown—that is why it is recommended to embed the code of the
test within a try statement.

The following is an example of a Selenium script with an implicit wait:

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

// Set an implicit wait for 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.
SECONDS);

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

// Verify expected changes to an element affected by
the test run
WebElement info = driver.findElement(By.id("lesson"));
if (info.getText().contains("run")) {
System.out.println("ImplicitWait worked, the
element contains 'run'");
} else {
System.out.println("Something went wrong with
ImplicitWait, 'run' was not found");
}
} finally {
driver.quit();
}
}

We are now able to understand what an implicit 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
18.117.189.7