
Hello guys,
The first post of the year will be a quick one. Took me a while to figure out since it has been ages I coded in Selenium/Java and used PageFactory (which I thought was deprecated, but it is just deprecated in C#)
If you ever come across an error like this when using PageFactory:
stale element reference: element is not attached to the page document
PageFactory initializes the elements the first time you run the automation and when the page changes (which happens on Angular and React pages) Selenium loses the reference to that element and needs to find it again with the new DOM.
You can do something like this:
protected void clickElement(WebElement element) {
try {
webDriverUtils.waitForElementToBePresent(element);
element.click();
} catch (StaleElementReferenceException e) {
PageFactory.initElements(driver, this);
}
Thanks for the article. I found your blog by searching “when not to use PageFactory” as I’m getting the strong feeling that PageFactory isn’t the best option for my current project. Then I started wondering if there are some newer automation tools out there that I should consider using instead of Selenium. So I was curious when you said you haven’t used Selenium and PageFactory in ages. What were you using for automation?
Nowadays I use testcafe or cypress for web tests
The magic ‘findElement()’ calls that PageFactory produces don’t protect against stale element references. They just create unrecoverable race conditions. If the DOM gets rebuilt between the time a reference is produced and the time it’s used, your test will fail. The only way to recover is to catch the exception, re-acquire the reference, and try the operation again.
This is the strategy I use in my Selenium framework.