Posted 24 days ago. Visible to the public. Repeats.

Raising JavaScript errors in Cucumber scenarios and how to silence them for particular scenarios

Raising JavaScript errors in Cucumber

With selenium JavaScript errors do not cause any failture in your cucumber scenarios. To archive a failture we can use the the Ruby bindings to Selenium Webdriver expose the Webdriver logging API introduced in version 2.38 .

The following step can be used:

Copy
Then /^there should be no JavaScript errors$/ do if alert_present? # Chrome 54 and/or Chromedriver 2.24 introduced a breaking change on how # accessing browser logs work. # # Apparently, while an alert/confirm is open, Chrome will block any requests # to its `getLog` API. # This causes Selenium to time out with a `Net::ReadTimeout` error else errors = page.driver.browser.manage.logs.get(:browser) errors.reject! do |error| case when error.level == 'WARNING' # CSS warnings, or similar error.message !~ /Deferred exception/ # error in promise when error.message.include?('Failed to load resource:') # Invalid images etc. true when error.message !~ %r(\Ahttp://127\.0\.0\.1:\d+/) # Errors on foreign domains (like twitter) true else false end end if errors.any? raise (['There are JavaScript errors:'] + errors.map(&:message)).join("\n\n") end end end

Wrapped in a AfterStep-Hook this step will force your test scenario to fail when JavaScript errors are raised.

Copy
AfterStep do step 'there should be no JavaScript errors' if selenium? end

This is almost always the desired behavior. However sometimes you want to ignore JavaScript errors explicitly.

How to silence them for particular scenarios

If you want to silence JavaScript errors, you can use a tag to exclude particular scenarios.

Copy
AfterStep 'not @silence_javascript_errors' do step 'there should be no JavaScript errors' if selenium? end

All Scenarios which are now tagged with @silence_javascript_errors will not fail on JavaScript errors.

This tag should only be used if you are 100% sure, that the Javascript error is the desired behavior. Don't use it to fix broken tests!!

If you don't want to ignore JavaScript errors completely in tagged scenarios, you can add the following step which prints the message to the cucumber console output.

Copy
AfterStep '@silence_javascript_errors' do errors = page.driver.browser.manage.logs.get(:browser) if errors.present? errors.each do |error| STDERR.puts 'WARNING: javascript error raised and ignored' STDERR.puts error.message end end end

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Natalie Krehan
Last edit:
17 days ago
by Natalie Krehan
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Natalie Krehan to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more