Saturday, August 25, 2018

If solving a (Selenium) Stale Element Exception with a “try-catch block” within “for loop” -- you are doing it wrong



In my opinion, a “try/catch” to handle stale element exception errors is simply a bad practice. The automation is expecting something, which clearly was not accessible in the DOM at the time it had been checked. There is a reason WHY. Find the WHY. Is there a wait that needs to be applied to an element or a group of elements? Is the automation using the correct ExpectedCondition on the element or does the element need an additional ExpectedCondition? Merely ignoring WHY will only lead to flakiness in the automation.

In my years of experience working with both Angular and React SPAs (Single Page Applications), there has never been an instance to wrap an element to handle any Selenium related errors. Not saying I have not experienced stale elements within the automation, what I am saying, there is a reason behind the stale element. I take the attitude that, “I don’t fully understand what is happening at that moment in time with my application and the automation, and I need to do some investigation”. By researching and analyzing the root cause, the automation engineer will have the understanding of the WHY, which is the key; furthermore, he or she will have insight on the resolution and how to address it accurately, thus totally eliminating the issue. Not to mention, by not adding this additional code overhead, the automation is cleaner and easier to reason about. 

For example, a co-worker begins to experience stale exception errors with the automation at random times. He implements the “try/catch” around every element before each command to “make sure it didn’t go stale”.  At some point it had slowed but it was not full proof.  A year plus later, a new automation engineer takes over the project, asked about the “try/catch” implementation and was updated on the reasons behind it. When the engineer requested my help, we were able to resolve the issue within 30 to 45 minutes and completely remove all the “try/catch” code, with no stale element exceptions there after.

Like I said, I have encountered stale elements and have endured the pain and torture of finding the WHY. And I am not going to try to convince anyone that, “its easy”.  Nevertheless, I just don’t believe in hiding flakiness within a try/catch statement—


The next post will focus on how to detect stale element exceptions with my concept of, “load testing your tests”.