In automation testing waits are used to halt or pause the execution of test cases for a certain amount of time before throwing an exception or moving to the next step.
The waits are essential when it comes to automation testing. In automation testing, sometimes the application doesn't work as we expect. In such scenarios we want the driver to wait for a certain amount of time before throwing an exception.
To fulfill the purpose we have different types of waits commands.
Selenium provides these three types of waits.
Implicit Wait
Explicit Wait
Fluent Wait
Let’s explore these waits in detail.
Implicit wait is a globally declared wait which means it will apply for each element in the entire duration for which the browser is open.
To implement implicit wait, import the following package.
import java.util.concurrent.TimeUnit;
Syntax:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Above line will implement implicit wait for 10 seconds for each element.
Explicit wait is used for specific conditions to fulfil before proceeding to another element or step. When we are not aware about the time element will take to load.
Explicit wait is more intelligent, but can only be applied for specified elements.
import org.openqa.selenium.support.ui.WebDriverWait
2. Then initialise the wait object.
WebDriverWait wait = new WebDriverWait(driver,30);
3. Apply a wait object for the Submit button to clickable.
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.
visibilityOfElementLocated
(By.xpath("//div[contains(text(),'Submit')]")));
Above code will implement Explicit wait for 30 seconds for the submit button to be clickable.
In Fluent Wait WebDriver waits for a certain time till the web element becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.
It checks web elements repeatedly at regular intervals until timeout happens or until the element is found. It is commonly used in Ajax applications. We can set a default polling period as needed.
Syntax:
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);
1.Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timeout of the wait
wait.withTimeout(600, TimeUnit.MILLISECONDS);
//Specify polling time
wait.pollingEvery(50, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)
//This is how we specify the condition to wait on.
wait.until(ExpectedConditions.alertIsPresent());
Thanks for Reading !
If you have any query Please let me know in comment section.