Introduction

 

Hi All,

In this post we explain how to detect Javascript Errors in firefox using selenium, watir webdriver and cucumber. If you are unfamiliar with these frameworks you can read up on our previous post about Web testing with cucumber.

Get JSErrorCollector

First, you need to get JSErrorCollector.xpi which you can get here. Then, store it under features/support/extensions in your cucumber project location.

 

Add JSErrorCollector.xpi to your browser profile

require 'rubygems'
require 'selenium-webdriver'
require 'watir-webdriver'
require 'logger'
 
#Start the logger
$log = Logger.new('log/selenium.log')
#Create a profile
profile = Selenium::WebDriver::Firefox::Profile.new
 
#Add JS error detection to the profile!
profile.add_extension "features/support/extensions/JSErrorCollector.xpi" rescue p "Cannot add JSErrorCollector.xpi to profile"

 

Launch a browser using the profile you created

Now you can launch a new browser instance using:

$BROWSER = Watir::Browser.new 'firefox', :profile => profile
$BROWSER.goto "http://www.spritecloud.com"

 

When the JSErrorCollector is installed successfully, you will see the error collector counter in the bottom right of the launched browser as displayed in the image below.

Collect the JS errors

First off, we create a separate method to get the JS errors formatted how you want to display them when one or more JS errors are detected.

#Function that returns a string that presents the details of the occurred JS errors
def get_js_error_feedback()
  jserror_descriptions = ""
  begin
    jserrors = $BROWSER.execute_script("return window.JSErrorCollector_errors.pump()")
    jserrors.each do |jserror|
      $log.debug "ERROR: JS error detected:n#{jserror["errorMessage"]} (#{jserror["sourceName"]}:#{jserror["lineNumber"]})"
 
      jserror_descriptions += "JS error detected:
   #{jserror["errorMessage"]} (#{jserror["sourceName"]}:#{jserror["lineNumber"]})
"
    end
  rescue Exception => e
    $log.debug "Checking for JS errors failed with: #{e.message}"
  end
  jserror_descriptions
end

 

Raise exception when JS error is detected

When using cucumber, you can create a hook after every teststep. In this hook we raise an exception when one or more JS errors are detected.

AfterStep do |scenario|
  raise get_js_error_feedback() unless get_js_error_feedback().empty?
end

Note that this is a Collector, so at the end of each execution, the JS errors of all the visited pages are collected. For speeding up the tests, you can do the check after the end of each scenario (use hook AfterScenario) and cleanup the list after that.

Good Luck!

top