Waits play an important role in executing tests in Selenium. Waits help user to troubleshoot issues while redirecting to different web pages. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes it difficult to locate elements. If an element is not yet present in the DOM(Document Object Model), code will throw an “ElementNotVisibleException” exception. Using waits we can solve this issue.
Selenium web driver provides 3 types of waits.
1. Implicit wait
2. Explicit wait
3. Fluent wait
In implicit wait, web driver polls the DOM for a certain duration when trying to find any element. This is useful when certain elements on the web page are not available immediately and need some time to load.
In the above code snippet, implicit wait is defined for only 10 seconds. Output will load within maximum waiting time of 10 seconds for that particular element.
Explicit wait is used to tell the web driver to wait for certain expected condition or maximum time exceeded before throwing “ElementNotVisibleException” exception.
Syntax: WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(element));
Few expected conditions are:
In the above code snippet, web driver will wait for maximum 10 seconds until the ExpectedCondition is met and here the condition is “elementToBeClickable”.
Fluent wait is used to define maximum time for the web driver to wait for a condition as well as the frequency with which we want to check the condition before throwing an “ElementNotVisibleException” exception. It checks for the web element at regular intervals until the element is found or timeout happens. Fluent wait command is useful when interacting with web elements that take longer duration to load.
Syntax: Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
Here, we are declaring the fluent wait with the timeout of 30 seconds and the frequency is set to 5 seconds by ignoring “NoSuchElementException” exception.
Implicit wait is a driver level wait and applicable to all the elements of the web page.
Explicit wait is applicable to only specified element mentioned always with “ExpectedConditions”. It is useful for verifying properties of the element as well.
Fluent wait is smart wait because it doesn’t wait for the maximum time specified in the statement instead it waits for the time till the condition specified becomes true.
Choose the best wait() statement based on your test execution need.