Wednesday 1 October 2014

Implicit and Explicit wait in Selenium Webdriver

There are two types of wait used in selenium webdriver.

  1. Implicit Wait
  2. Explicit wait
Implicit wait:
We can instruct the browser to wait up to a certain amount of time before throwing a not element found exception. When the page or a component of a page is loaded, it waits up to the time that is declared at the implicit wait command. If the page or component is not loaded with in this time period, then selenium Webdriver throws an exception that the specific element is not found. Declaring wait command for a webdriver object will stay up to its life time until the driver is closed.

driver.manage().timeouts().implicitlyWait(time period,TimeUnit.SECONDS);
time period : Here time value is given as input. How many seconds the driver has to wait is given here.
TimeUnit.SECONDS : Time period is measured as second here. You can use other time unit like day, hour etc.

Example (Java) :
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
Implicit wait can make executing scripts slower.

Explicit wait:
Explicit wait is used to define wait command for a single component load or single condition execution. It only waits for the single component load or single lines execution. There are two classes WebDriverWait and ExpectedConditions for this purpose.
WebDriverWait wait = new WebDriverWait(driver, time period);
wait.until(ExpectedConditions.textToBePresentInElement(By.xpath(getTxtVerifyTitle()), Text Title));

time period : Here time value is given as input. How many seconds the driver has to wait is given here.

Example (Java) :
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.textToBePresentInElement(By.xpath(getTxtVerifyTitle()), "Verify Email"));

ExpectedConditions class has some conditions.

alertIsPresent() // Is Alert Present?
elementSelectionStateToBe // Is the element selected?
elementToBeClickable // Is the element clickable?
elementToBeSelected // Element is selected
frameToBeAvailableAndSwitchToIt // Is frame available and selected?
invisibilityOfElementLocated // Is the element invisible?
presenceOfAllElementsLocatedBy // All elements presence location.
refreshed // Wait for a page refresh.
textToBePresentInElement // Is the text present for a particular element?
textToBePresentInElementValue // Is the element value present for a particular element?
visibilityOf // Is the element visible?
titleContains // Is that title contain?