Capturing JavaScript error in Selenium

Baz1nga picture Baz1nga · Nov 15, 2010 · Viewed 57.3k times · Source

Is there a way to capture errors occurring in the DOM in Selenium and probably flag the same as an error in the page?

To give a brief example, let's say I'm trying to bind an event on a non-existing HTML control, my browser throws an error saying:

element abcd not found in the console.

Now, if I want the same error to fail my selenium tests and the message that is shown on the browser is shown as the error message.

Is it possible to do something like this?

Answer

magnusarinell picture magnusarinell · Mar 16, 2016

I'm doing this to capture JavaScript errors:

[TestCleanup]
public void TestCleanup()
{
    var errorStrings = new List<string> 
    { 
        "SyntaxError", 
        "EvalError", 
        "ReferenceError", 
        "RangeError", 
        "TypeError", 
        "URIError" 
    };

    var jsErrors = Driver.Manage().Logs.GetLog(LogType.Browser).Where(x => errorStrings.Any(e => x.Message.Contains(e)));

    if (jsErrors.Any())
    {
        Assert.Fail("JavaScript error(s):" + Environment.NewLine + jsErrors.Aggregate("", (s, entry) => s + entry.Message + Environment.NewLine));
    }
}