0 votes
1 view
in DevOps and Agile by (19.8k points)

When using implicit waits, as advised here, I still sometimes want to assert the immediateinvisibility or non-existence of elements.

In other words, I know some elements should be hidden, and want my tests to 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?

1 Answer

0 votes
by (63.4k points)

Given that Selenium doesn't seem to offer what I want directly, this simple helper method is what I used 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...