Why are waits required in Selenium?
In UI automation, waits are required due to the fact positive elements get loaded at the web page asynchronously, so after triggering an event a web page might also get loaded correctly however a number of its factors may still no longer get loaded. This causes elementNotFound exception whilst finding the detail. In such instances, we are left with using Thread.Sleep() i.E. A static wait with a purpose to halt the test execution for some precise time after which carry out the following step. As Thread.Sleep() will watch for the desired time regardless of if the elements get seen earlier than that point. So, the usage of Thread.Sleep() is in no way really helpful in UI automation.
To avoid this selenium gives one-of-a-kind types of waits out of which Implicit and specific waits are maximum normally used.
An implicit wait while used is about to the WebDriver example and is carried out to all the internet elements. In implicit wait the webdriver polls the DOM to test the provision of the webElement and waits until the maximum time detailed earlier than throwing NoSuchElementException.
WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
In the above code snippet, the value 20 laid out in implicit wait approach is the maximum time in seconds until which webDriver will wait before throwing NoSuchElementException while locating a webElement.
Unlike implicit waits, the explicit waits are implemented to each and every webElement. In explicit wait, certain situations are defined for which the webDriver instance waits earlier than finding webElements or performing movements on them. Some of the maximum common conditions laid out in express waits are-
elementToBeClickable, presenceOfElementLocated etc.
WebDriverWait wait = new WebDriverWait(driver, 15); wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
Here the webDriver example will wait until the situation unique is met i.E. The presence Of Element placed with the aid of the ElementLocator with the maximum wait time of 15 seconds and then if the situation continues to be not met then it's going to throw an exception.