Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture JavaScript errors with Selenium WebDriver using Java

I was wondering if there is a way to capture JavaScript errors on a page while running automated Selenium tests.

like image 933
megadevices Avatar asked Mar 27 '18 07:03

megadevices


3 Answers

There is logs Beta version in WebDriver

driver.manage().logs().get(LogType.BROWSER);

Will give you the console content.

Then you can filter it using Level

LogEntries entries = driver.manage().logs().get(LogType.BROWSER);
entries.filter(Level.SEVERE);
like image 134
Guy Avatar answered Oct 04 '22 21:10

Guy


And there is one that worked for me. Here it is.

    public boolean isThereJSErrorOnThePage() {
    Set<String> errorStrings = new HashSet<>();
    errorStrings.add("SyntaxError");
    errorStrings.add("EvalError");
    errorStrings.add("ReferenceError");
    errorStrings.add("RangeError");
    errorStrings.add("TypeError");
    errorStrings.add("URIError");
    LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
    for (LogEntry logEntry : logEntries) {
        for (String errorString : errorStrings) {
            if (logEntry.getMessage().contains(errorString)) {
                LOGGER.error("Java Script error has been detected:");
                LOGGER.error(new Date(logEntry.getTimestamp()) + " " + logEntry.getLevel() + " " + logEntry.getMessage());
                return true;
            }
        }
    }
    return false;
}

If it does not work out of a box, try to add capabilities:

DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(desiredCapabilities);
like image 28
megadevices Avatar answered Oct 04 '22 21:10

megadevices


you can try https://github.com/AutomatedOwl/chromedriver-js-errors-collector it captures all the js errors and attaches them to allure report.

like image 36
Nir Tal Avatar answered Oct 04 '22 20:10

Nir Tal