Equivalent of Waitforvisible/Waitforelementpresent in Selenium Webdriver Tests Using Java

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 certain
amount of time when trying to find an element or elements if they are
not immediately available. The default setting is 0. Once set, the
implicit 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 condition
to occur before proceeding further in the code. The worst case of this
is Thread.sleep(), which sets the condition to an exact time period to
wait. There are some convenience methods provided that help you write
code that will wait only as long as required. WebDriverWait in
combination with ExpectedCondition is one way this can be
accomplished.

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

Waiting Results not always the same

StaleElementReference exception comes when the element you are trying to interact is no longer in the dom or has become stale. So, you need to refresh the page and then again fetch the element and it would work.

So, please add driver.navigate().refresh(); line of code before the element on which you are getting the exception and then operate on the element and it would work fine.

Temporarily bypassing implicit waits with WebDriver

Given that Selenium doesn't seem to offer what I want directly (based on what Mike Kwan and Slanec said), this simple helper method is what I went with for now:

protected boolean isElementHiddenNow(String id) {
turnOffImplicitWaits();
boolean result = ExpectedConditions.invisibilityOfElementLocated(By.id(id)).apply(driver);
turnOnImplicitWaits();
return result;
}

private void turnOffImplicitWaits() {
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
}

private void turnOnImplicitWaits() {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

If the element is hidden or not present at all, the method returns true; if it is visible, returns false. Either way, the check is done instantly.

Using the above is at least much cleaner than littering the test cases themselves with calls to turnOffImplicitWaits() and turnOnImplicitWaits().

See also these answers for fined-tuned versions of the same approach:

  • Using try-finally to turn implicit waits back on
  • Using By locator as the parameter


Related Topics



Leave a reply



Submit