Question

I have a Selenium test suite in Java, using WebDriver. I have a generic wait function in place that takes a CSS selector and wait for the element to become present and visible before moving on to assertions, using WebDriverWait. Now, though, I want to have something that waits for all elements of a certain type, that are in the DOM to not be visible anymore, before proceeding. The exact example is that I have a number of images being loaded and I want to wait for their loading spinners to disappear before continuing. Haven't been able to find something that would solve this for me yet, so posting it here. Any clues?

Thanks!

public void waitForPageToLoad(WebDriver webDriver, String cssToWaitFor) {
    WebDriverWait wait = new WebDriverWait(webDriver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssToWaitFor)));
}
Was it helpful?

Solution

Check the invisibilityOfElementLocated expected condition. Reference. From the doc:

invisibilityOfElementLocated

public static ExpectedCondition<java.lang.Boolean> invisibilityOfElementLocated(By locator)

An expectation for checking that an element is either invisible or not present on the DOM.

Parameters:
    locator - used to find the element

So you could use it like:

public void waitForInvisibility(WebDriver webDriver, String cssToWaitFor) {
    WebDriverWait wait = new WebDriverWait(webDriver, 20);
    wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(cssToWaitFor)));
}

Alternatively you can look into public static ExpectedCondition<java.lang.Boolean> not(ExpectedCondition<?> condition), which by the doc does:

An expectation with the logical opposite condition of the given condition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top