When using implicit waits, as advised here, I still sometimes want to assert the immediate invisibility or non-existence of elements.
In other words, I know some elements should be hidden, and want my tests make that assertion fast, without spending several seconds because of the (otherwise useful) implicit wait.
One thing I tried was a helper method like this:
// NB: doesn't seem to do what I want
private boolean isElementHiddenNow(String id) {
WebDriverWait zeroWait = new WebDriverWait(driver, 0);
ExpectedCondition<Boolean> c = invisibilityOfElementLocated(By.id(id));
try {
zeroWait.until(c);
return true;
} catch (TimeoutException e) {
return false;
}
}
But in the above code, the call to until()
only returns after the implicit wait time has passed, i.e., it doesn't do what I wanted.
This is the only way I've found so far that works:
@Test
public void checkThatSomethingIsNotVisible() {
turnOffImplicitWaits();
// ... the actual test
turnOnImplicitWaits();
}
... where e.g. turnOffImplicitWaits()
is a helper in common Selenium superclass:
protected void turnOffImplicitWaits() {
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
}
But that is not very elegant, I think. Is there any cleaner way to bypass the implicit wait occasionally?
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: