Why are waits required in Selenium?
In UI automation, waits are required because certain elements get loaded on the page asynchronously, so after triggering an event a page may get loaded successfully but some of its elements may still not get loaded. This causes element not found exception while locating the element. In such cases, we are left with using Thread.sleep() i.e. a static wait that will halt the test execution for some specified time and then perform the next step. As Thread.sleep() will wait for the specified time no matter if the elements get visible before that time. So, using Thread.sleep() is never advisable in UI automation.
To avoid this selenium provides different types of waits out of which Implicit and explicit waits are most commonly used.
- Implicit Waits –
An implicit wait when used is set to the WebDriver instance and is applied to all the web elements. In implicit wait, the web driver polls the DOM to check the availability of the web element and waits until the maximum time specified before throwing NoSuchElementException.
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
In the above code snippet, the value 20 specified in the implicit wait method is the maximum time in seconds till which webDriver will wait before throwing NoSuchElementException while locating a web element.
- Explicit Waits –
Unlike implicit waits, the explicit waits are applied to each and every web element. In explicit wait, certain conditions are defined for which the webDriver instance waits before locating web elements or performing actions on them. Some of the most common conditions specified in explicit waits are-
elementToBeClickable, presenceOfElementLocated etc.
WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
Here the webDriver instance will wait until the condition specified is met i.e. the presence Of Element located by the ElementLocator with the maximum wait time of 15 seconds after which if the condition is still not met then it will throw an exception.