Monday, May 18, 2020

Wait commands in Selenium WebDriver

In automation testing, wait commands direct the test execution to pause for a certain length of time before moving onto the next step. This enables WebDriver to check if one or more web elements are present/visible/enriched/clickable, etc.

In Selenium WebDriver, to sync up scripts there are four types of wait:
  • Page Load Timeout
  • Implicit Wait
  • Explicit Wait
  • Fluent Wait

Page Load Timeout:
This is the maximum time selenium waits for a page to load successfully on a browser. If the page takes more than this time, it will throw a Timeout Exception.
driver.manage().timeouts().pageLoadTimeout(90, TimeUnit.SECONDS);

Here Selenium WebDriver instance will wait a maximum of 90 seconds for a webpage to load. If it is loaded before the specified wait time, the execution will move to the next line of the script. If it doesn’t get loaded in 90 seconds it will throw the Timeout Exception.

Implicit Wait
It the maximum time (Threshold value), selenium code waits to interact with that Web Element, before throwing “Element not found
exception”.
Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs
To add implicit waits in test scripts, import the following package.
import java.util.concurrent.TimeUnit;

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Add the above code into the test script. It sets an implicit wait after the instantiation of WebDriver instance variable.


Explicit Wait
This wait can be considered as conditional wait and is applied to a particular Web Element with a condition.
public void waitTillElementVisible(){
WebDriverWait wait = new WebDriverWait(Driver, 90);
wait.until(ExpectedConditions.visibilityOfElementsLocatedBy(By.xpath("//input[@type='text']")));
}

Here, the reference variable is named <wait> for the <WebDriverWait> class. It is instantiated using the WebDriver instance.

To use Explicit Wait in test scripts, import the following packages into the script.
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
In order to declare explicit wait, one has to use “ExpectedConditions”. The following Expected Conditions can be used in Explicit Wait.
  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Fluent Wait
In Fluent wait, a maximum time is defined to wait for a condition and along with that polling time is also defined. Polling time is the frequency with which the condition is checked. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
To put it simply, Fluent Wait looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.
public static void fluentWait(WebDriver driver, int timeout, int pollingTime, By by){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(timeout))
.pollingEvery(Duration.ofSeconds(pollingTime))
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
}
In this code, the maximum time to wait is passed as timeout, polling time (a frequency with which condition is checked again) is passed as “pollingTime” and we are waiting for a condition to get true i.e. visibility of Element located by.
package com.automation.eng.AutomationProject;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
public class WaitTime {
private WebDriver driver;
private String baseUrl;
@BeforeMethod
public void setUp() throws Exception {
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create driver object for Chrome
driver = new ChromeDriver();
// Maximize the browser window
driver.manage().window().maximize();
//Delete all cookies
driver.manage().deleteAllCookies();
//Navigate to a URL
baseUrl = "https://javaqaeng.blogspot.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testUnited() throws Exception {
driver.get(baseUrl);
//Assert title
String actualTitle = driver.getTitle();
String URL = driver.getCurrentUrl();
//Get title of page - printing title of page
System.out.println("My page title is :" + actualTitle);
//Get URL
System.out.println("My URL is: " + URL);
String expectedTitle =
"FREE Professional Java Developer, Automation Engineer, Business Analyst Training";
//Assert my title
assertEquals(expectedTitle,actualTitle);
//Another way of assertion - it does not need to all title for assertion
assertTrue(driver.getTitle().contains("FREE Professional Java Developer"));
// OR Verify expected page title and actual page title is same
Assert.assertTrue(actualTitle.equalsIgnoreCase(expectedTitle
),"FREE Professional Java Developer, Automation Engineer, Business Analyst Training");
//OR you can use if/else - please do not confuse - it is optional
if(driver.getTitle().contains("FREE Professional Java Developer"))
//Pass
System.out.println("Page title contains \"FREE Professional Java Developer\" ");
else
//Fail
System.out.println("Page title doesn't contains \"FREE Professional Java Developer\" ");
// explicit wait - to wait for the compose button to be click-able
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='PopularPosts1']/h2")));
// print heading when it is visible
System.out.println("My bottom title is: " + driver.findElement(By.xpath("//div[@id='PopularPosts1']/h2")).getText());
}
@AfterMethod
public void tearDown() throws Exception {
// closes all the browser windows opened by web driver
driver.quit();
}
}
/*/
*
* My page title is :FREE Professional Java Developer, Automation Engineer, Business Analyst Training
My URL is: https://javaqaeng.blogspot.com/
Page title contains "FREE Professional Java Developer"
My bottom title is: Popular Posts
PASSED: testUnited
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================
*/

No comments:

Post a Comment