如何使用Java使用Selenium WebDriver捕获JavaScript错误

时间:2018-03-27 07:28:09

标签: java selenium

我想知道是否有办法在运行自动Selenium测试时捕获页面上的JavaScript错误。

5 个答案:

答案 0 :(得分:6)

WebDriver

中有logs测试版
driver.manage().logs().get(LogType.BROWSER);

将为您提供控制台内容。

然后您可以使用Level

过滤它
LogEntries entries = driver.manage().logs().get(LogType.BROWSER);
entries.filter(Level.SEVERE);

答案 1 :(得分:1)

还有一个对我有用。在这里。

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

如果它无法使用,请尝试添加功能:

DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(desiredCapabilities);

答案 2 :(得分:1)

您可以尝试https://github.com/AutomatedOwl/chromedriver-js-errors-collector 它捕获所有js错误,并将它们附加到诱人的report

答案 3 :(得分:0)

尝试以下代码来捕获webPage的javascript错误,并告诉我它是否帮助了你

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

答案 4 :(得分: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();
    }
}

如果您只需要打印 JavaScript 错误,可以使用方法 printJavaScriptErrors()

如果在出现 JavaScript 错误时需要让测试失败,可以使用 checkJavaScriptErrorsAreNotAvailable(Level level)

由于使用了SoftAssert,当测试失败时会显示所有相关级别的错误。