1
votes

I'm trying to test the web site using Page Object, When I'm executing my scripts, I'm getting Element is no longer attached to the DOM (Selenium::WebDriver::Error::StaleElementReferenceError) error message intermittently while calling a function.

How can I overcome from this issue, If any suggestions?

3

3 Answers

2
votes

We also faced the same problem in our project. One way of overcoming this is to use a try catch block within the method which is causing this problem. Inside the catch block again re execute the same lines of code/another method. This will take care of the issue.

2
votes

You get this exception when the element you are interacting with has been changed in the DOM. If you capturing the element in the WebElement object and then using that object further to perform some clicks/typing and if in between the reference to that element changed, then the object you are using will no longer refer to a correct locator. Try using the element locators at the time of interacting with the element instead of capturing it in a WebElement object first and then using that object further.

E.g. instead of doing :

WebElement e = driver.findElement(By.id("someID"));
e.click();
.
.
.
e.click();

try to use :

driver.findElement(by.id("someID")).click();
.
.
.
driver.findElement(by.id("someID")).click();

Otherwise, you can use Vinay's method.

0
votes

Use PageFactory to initialize your page objects. It will create lazy proxies to the actual element.

public class PageObject {
   @FindBy(id="someID")
   private WebElement someElement;

   public void doSomething() {
      someElement.click();  
   }
}

PageObject po = PageFactory.initElements(driver, PageObject.class);

If you do not use @CacheLookup along with @FindBy, any time you use someElement, it will go and look for this element using the finder.