I was wondering if there is a way to capture JavaScript errors on a page while running automated Selenium tests.
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);
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);
you can try https://github.com/AutomatedOwl/chromedriver-js-errors-collector it captures all the js errors and attaches them to allure report.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With