1.

A fresher in your team encounters a ‘StaleElement’ exception while executing an automated test suite. How will you help them solve this issue?

Answer»

There are two causes for this exception. Element in the web page that was a part of the current instance has been refreshed or navigated to another web page.  This causes the element to be destroyed or reconstructed. The second reason is that the element is no longer attached to the DOM. These are the breakthroughs that I will provide my team members with to solve this issue:

  • You can try refreshing the webpage using the navigate command.
driver. navigate().refresh()
driver.findElement (By.xpath(“sample”)).click();
  • You can use a try-catch block within a for loop if the element is not attached to the DOM
for(int i=0;i<=2;i++)
{ try { driver.findElement(By.xpath("sample")).click();
break; }
Catch (Exception e){
Sysout(e.getMessage());
}
}
  • If you are sure that the element will be available, use the ExpectedConditions.refreshed method to avoid the StaleElementReference exception. This method updates the element by redrawing it and providing access to the referenced element.
wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("sample")));


Discussion

No Comment Found