Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java? Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java? selenium selenium

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?


Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certainamount of time when trying to find an element or elements if they arenot immediately available. The default setting is 0. Once set, theimplicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain conditionto occur before proceeding further in the code. The worst case of thisis Thread.sleep(), which sets the condition to an exact time period towait. There are some convenience methods provided that help you writecode that will wait only as long as required. WebDriverWait incombination with ExpectedCondition is one way this can beaccomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);WebElement element = wait.until(        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));


WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.


WebDriverWait wait = new WebDriverWait(driver, 10);WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

Element is Clickable - it is Displayed and Enabled.

From WebDriver docs: Explicit and Implicit Waits


Well the thing is that you probably actually don't want the test to run indefinitely. You just want to wait a longer amount of time before the library decides the element doesn't exist. In that case, the most elegant solution is to use implicit wait, which is designed for just that:

driver.manage().timeouts().implicitlyWait( ... )