Sunday 31 July 2016

Finding JavaScript errors through Webdriver

        Now a days it became very common that many of the applications are using extensive java script for the client side transactions. So, from the QA perspective it is very important to validate those Java script errors irrespective of whether those errors or warnings affect the application in near future or not. There are options like firebug, chrome developer tool, IE Developer tool, which gives the java script errors on their consoles. 

         We can automate this by using Selenium Web driver API. Below code snippet can be used to get those java script errors. Here I used one sample site which has some java script errors

     public void consoleEntries(LogEntries consoleEntries) {
         for (LogEntry logEntry : consoleEntries) {
               System.out.println("Log Level: " + logEntry.getLevel().toString());
               System.out.print(" Log Message: " + logEntry.getMessage().toString());
          }
    }


  @Test
  public void getJavaScriptErrors() throws Exception {
  String url = "http://www.softwaretestingtricks.com/";
  WebDriver webDriver = new FirefoxDriver();
  webDriver.get(url);
   LogEntries logEntries = webDriver.manage().logs().get(LogType.BROWSER);
   consoleEntries(logEntries);
  webDriver.quit();
  }


To reduce the no.of logs, we can set the log preferences. So, that we will get only desired logs. That can be done as below

        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
LoggingPreferences loggingPreferences = new LoggingPreferences();
loggingPreferences.enable(LogType.BROWSER, Level.SEVERE);
desiredCapabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences);
webDriver = new FirefoxDriver(desiredCapabilities);