5

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

5 Answers 5

9

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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

Comments

0

Try the below code for capturing the javascript error of webPage and let me know if it has helped you

import java.util.List;
import java.util.concurrent.TimeUnit;
import net.jsourcerer.webdriver.jserrorcollector.JavaScriptError;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class jsError {
 WebDriver driver;

 @BeforeTest
 public void setup() throws Exception {
  FirefoxProfile profile = new FirefoxProfile();
  JavaScriptError.addExtension(profile);
  driver = new FirefoxDriver(profile);
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://only-testing-blog.blogspot.com/2015/01/table-with-checkbox.html");
 }

 @Test
 public void printPageErrors() throws Exception {
  //Capture all errors and store them In array.
  List<JavaScriptError> Errors = JavaScriptError.readErrors(driver);
  System.out.println("Total No Of JavaScript Errors : " + Errors.size());
  //Print Javascript Errors one by one from array.
  for (int i = 0; i < Errors.size(); i++) {
   System.out.println("Error Message : "
     + Errors.get(i).getErrorMessage());
   System.out.println("Error Line No : "
     + Errors.get(i).getLineNumber());
   System.out.println(Errors.get(i).getSourceName());
   System.out.println();
  }
 }
}

Comments

0
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;

import java.util.Date;
import java.util.logging.Level;

public class LoginTest {

    private WebDriver driver;

    @BeforeMethod
    public void setPreConditions() {
        WebDriverManager.chromedriver().setup();
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        LoggingPreferences loggingPreferences = new LoggingPreferences();
        loggingPreferences.enable(LogType.BROWSER, Level.ALL);
        capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences);
        driver = new ChromeDriver(capabilities);

        driver.manage().window().maximize();
        driver.get("your_web_application_url");

        // Put a wait condition if needed.
    }

    @Test
    public void checkJavaScriptErrors() {
        checkJavaScriptErrorsAreNotAvailable(Level.SEVERE);
    }

    @AfterMethod
    public void quit() {
        driver.quit();
    }

    private void printJavaScriptErrors() {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
        }
    }

    private void checkJavaScriptErrorsAreNotAvailable(Level level) {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        SoftAssert softAssert = new SoftAssert();
        for (LogEntry entry : logEntries) {
            if (entry.getLevel().equals(level)) {
                softAssert.fail(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
            }
        }
        softAssert.assertAll();
    }
}

If you only need to print the JavaScript errors, you can use the method printJavaScriptErrors()

If you need to fail the test when there are JavaScript errors, you can use checkJavaScriptErrorsAreNotAvailable(Level level).

Since the SoftAssert is used, it will show all the relevant level errors when the test is failed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.