Common Causes
A
stale element reference exception is thrown in one of two cases, the first
being more common than the second:
- The element has been deleted entirely.
- The element is no longer attached to the DOM.
The Element has been Deleted
The
most frequent cause of this is that page that the element was part of has been
refreshed, or the user has navigated away to another page. A less common, but
still common cause is where a JS library has deleted an element and replaced it
with one with the same ID or attributes. In this case, although the replacement
elements may look identical they are different; the driver has no way to
determine that the replacements are actually what's expected.
If
the element has been replaced with an identical one, a useful strategy is to
look up the element again. If you do this automatically, be aware that you may
well be opening your tests to a race condition and potential flakiness. For
example, given the code:
WebElement element = driver.findElement(By.id("example"));
String text = element.getText();
If
"element.getText" returns before the element is removed from the DOM
you'll get one result. If, however, the element is removed from the DOM and
your code does an automatic lookup for the element again before "element.getText"
a different result may be returned.
Should
you wish to head down this route, the simplest hook point is to call setElementConverter.
The Element is not Attached to the DOM
A
common technique used for simulating a tabbed UI in a web app is to prepare
DIVs for each tab, but only attach one at a time, storing the rest in
variables. In this case, it's entirely possible that your code might have a
reference to an element that is no longer attached to the DOM (that is, that
has an ancestor which is "document.documentElement").
0 Comments