Tuesday, July 15, 2014

Part 2 Troubleshooting WebDriver StaleElementReferenceException

StaleElementReferenceException can be a misleading error and people can have a hard time filtering out the actual root cause. The StaleElementReferenceException means the element has been removed or changed in between the time it was referenced and the time it was used.

Let’s walk through some code that might result in a StaleElementReferenceException

  1) We create a variable initialized to a text box
var text1 = driver.FindElement(By.Id("text1"));
  2) Lets imagine some javascript removed it from DOM and then adding it back
  3) Finally the call to SendKeys() will throw "StaleElementReferenceException"
text1.SendKeys("StaleElementReferenceException");

I often see this error on SelectElement's
For example:
A form with dependent SelectElement's: a SelectElement for State that depending on it value populates a SelectElement for City.
When you populate the State SelectElement, the data is loaded into the City SelectElement by removing it from DOM and then adding it back. Lots of apps have these dependent SelectElement's
You can create a variable for the City SelectElement before populating the State but theres might be a race condition if you try t populate it right after populating the State.

Here is a link to the Selenium2 Webdriver documentation on StaleElementReferenceException.

Links to Troubleshooting:
Part 0 Troubleshooting WebDriver issues are easy and so can you!
Part 1 Troubleshooting WebDriver NoSuchElementException
Part 2 Troubleshooting WebDriver StaleElementReferenceException