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?
My implementation:
With extension method:
And class:
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:
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()
andturnOnImplicitWaits()
.See also these answers for fined-tuned versions of the same approach:
By
locator as the parameterIn an existing code relying a lot on implicit wait way of thinking, and without CSS to the rescue, I found a way out nfor that kind of things, complementing it with Jsoup, and going on with Jsoup:
I would also suggest changing the parameter to a "By" locator for more flexibility when looking for the element.
That way, you could search by css if needed rather than just id:
'Course, your locator should probably be designed to return only one element (unlike the "By" example I quickly grabbed, which returns all part links in a css table of rows...) So, an "id" example would look like
My approach was to bypass Implicit wait entirely and reimplement it (with an addition of a visibility check etc.) in my own
findElement()
andfindElements()
methods which I now use by default. This way, when I want to check something instantly, I can call the original WebDriver method which does, of course, not wait.@Jonic's answer helped me, however I would add a
try { } finally { }
and callturnOnImplicitWaits()
in thefinally
block to make sure it always turns back on.