Tuesday, 7 May 2019

Interview | How can you solve StaleElementReferenceException

How can you solve StaleElementReferenceException

Answer : ExpectedConditions.refreshed

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.


public WebElement waitForElementToBeRefreshedAndClickable(WebDriver driver, By by) {
    return new WebDriverWait(driver, 30)
            .until(ExpectedConditions.refreshed(
                    ExpectedConditions.elementToBeClickable(by)));
}

So basically, this is a method that waits until a DOM manipulation is finished on an object.

When the DOM has manipulated, and say after clicking a button, adds a class to that element. If you try to perform an action on said element, it will throw StaleElementReferenceException since now the  WebElement returned now does not represent the updated element.

You'll use refreshed when you expect DOM manipulation to occur, and you want to wait until it's done being manipulated in the DOM.

No comments:

Post a Comment