【问题标题】:How to capture JavaScript errors with Selenium WebDriver using Java如何使用 Java 使用 Selenium WebDriver 捕获 JavaScript 错误
【发布时间】:2018-09-05 12:02:05
【问题描述】:

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

【问题讨论】:

    标签: java selenium selenium-webdriver webdriver


    【解决方案1】:

    WebDriver中有logs测试版

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

    会给你控制台内容。

    然后你可以使用Level过滤它

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        你可以试试https://github.com/AutomatedOwl/chromedriver-js-errors-collector 它捕获所有 js 错误并将它们附加到 allure report

        【讨论】:

          【解决方案4】:

          尝试下面的代码来捕获网页的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();
            }
           }
          }
          

          【讨论】:

            【解决方案5】:
            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,所以在测试失败时会显示所有相关级别的错误。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-07-10
              • 2014-10-15
              • 2015-04-22
              • 2021-02-28
              • 2018-01-03
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多