Capturing Javascript Errors in Selenium

Here at Linn we write automated acceptance tests using SpecFlow and Selenium, targeting Google Chrome. For the most part these tests run pretty well, but from time to time we run across test failures which prove difficult to diagnose. This week I ran across one such error – I knew error messages must be being displayed from the javascript code in Chrome’s console, but I had no way of seeing that information when the tests were run in Selenium. Worse still, I couldn’t replicate the issue locally.

One of my colleagues suggested that perhaps there was a way to capture and log the errors from Chrome’s console for later examination, and it turns out there is, using the rather handy ChromeJSErrorCollector extension.

Having grabbed a copy of the packed extension.crx file and included it in the Visual Studio solution, theĀ first step was to get Selenium to run that extension on the instance of Chrome used for the tests:

var options = new ChromeOptions();
options.AddExtension("extension.crx");
var driver = new ChromeDriver(options);

Following this we execute the test code itself as standard. Then at the end of the test, we need to have a look for errors:

var javascriptDriver = driver as IJavaScriptExecutor;
var errors = javascriptDriver.ExecuteScript("return window.JSErrorCollector_errors ? window.JSErrorCollector_errors.pump() : []");

The javascript being executed here is key – it’s querying the extension for errors and pumping them out to a javascript object which is then returned to us.

Unfortunately that object isn’t particularly nicely typed, so we need the following slightly ugly code to turn the object into useful output:

var writer = new StreamWriter("jsErrors.log");
var collection = errors as ReadOnlyCollection<object>;
foreach (var item in collection)
{
    var errorObject = item as Dictionary<string, object>;
    foreach (var field in errorObject)
    {
       writer.WriteLine(field.Key + " - " + field.Value);
    }
    writer.WriteLine("-------------------");
}
writer.Flush();
writer.Close();

Presto! We get text output of any errors from the log file for diagnosis. Useful stuff, especially when used in combination with Selenium’s ability to save screenshots.

Advertisements
This entry was posted in Code and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s