An implicit wait directs WebDriver to poll the DOM for a specified amount of time when trying to locate an element. If the element is not immediately available, WebDriver will wait for the defined duration before throwing an exception.
By default, the implicit wait is set to 0 seconds. Once set, it remains effective for the entire lifespan of the WebDriver object instance.
Example of setting an implicit wait for 10 seconds:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Wait + Expected Conditions:
Explicit waits are code structures you define to wait for a specific condition to be met before proceeding further in the code execution. Unlike implicit waits, explicit waits are more flexible and responsive, avoiding the need to wait for a fixed time duration like Thread.sleep().
One effective way to implement an explicit wait is using WebDriverWait in combination with ExpectedConditions. This approach allows WebDriver to wait dynamically until the expected condition (such as visibility of an element) is met or a timeout occurs.
Example using WebDriverWait to wait until an element with id “someid” becomes visible:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someid")));
In this example:
WebDriverWait is instantiated with a timeout of 10 seconds (new WebDriverWait(driver, 10)).
ExpectedConditions.visibilityOfElementLocated(By.id(“someid”)) specifies the condition to wait for—visibility of the element identified by “someid”.
The wait.until() method waits until the expected condition returns a non-null value (indicating the condition is met) or throws a TimeoutException if the condition is not met within the specified timeout period.
Using explicit waits with ExpectedConditions enhances test reliability by allowing WebDriver to synchronize with the application’s dynamic behavior, making tests more robust and less prone to timing issues compared to using implicit waits or fixed sleep times.