Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

0 like 0 dislike
128 views
by The go-to Tester (158 points)
retagged by
I have over 100 autotests. Sometimes some of them accidentally fall with StaleElementRefereException. How to avoid this error?

1 Answer

1 like 0 dislike
by The go-to Tester (181 points)
selected by
 
Best answer

StaleElementRefereException occures when element was fetched before you navigate from that page or refresh the page. Also, it happnes sometimes while working with Ajax calls.

 

e.g.

List<WebElement> elements = driver.findElements(By.tagName("tr")); // this will return all tr (table rows in the page)

while(WebElement element : elements){

driver.navigate().refresh(); //I am refreshing the page.

element.click(); // this line will throw StaleElementRefereException 

}

To overcome above error, we usually refetch the element everytime after completing refresh or page navigation.

eg.

List<WebElement> elements = driver.findElements(By.tagName("tr"));

for(int i=0; i < elements.size(); i++){

driver.navigate().refresh(); //I am refreshing the page.

elements = driver.findElements(By.tagName("tr")); //I refetch all elements

elements.get(i).click(); //this will work

}

Hope that helps! Reply to this comment with your code and exact exception you are getting, so that I can help you with better solution.

by The go-to Tester (158 points)
by The go-to Tester (181 points)
Glad it helped.


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

...