Catch Javascript errors in your system tests

How to make your tests fail in case of Javascript errors with capybara and chrome headless

Alessandro Rodi
Mar 8, 2018 · 2 min read
Image for post
Image for post

Let’s be honest, as Rails developers, we are not really used to test of Javascript a lot. Maybe because we don’t have a lot of it, maybe because we are just lazy. And is not that hard! Please look at jasmine-rails. It works great and you should definitely use it.

Yesterday I deployed to production a very embarrassing JS bug. It was embarrassing because it was logged in the console, and it was in the Homepage. I mean: you had to do nothing particular to find it, it was just there in the first page of my application. It was not preventing it from working, otherwise my system tests would have caught it, but it was presenting an annoying red cross.

Image for post
Image for post

“Why can’t I catch it in my system tests?” I thought. And I decided to add this to my rails_helper.rb.

config.after(:each, type: :system, js: true) do
errors = page.driver.browser.manage.logs.get(:browser)
if errors.present?
aggregate_failures 'javascript errrors' do
errors.each do |error|
expect(error.level).not_to eq('SEVERE'), error.message
next unless error.level == 'WARNING'
STDERR
.puts 'WARN: javascript warning'
STDERR
.puts error.message
end
end
end
end

This script has been tested with headless_chrome and Capybara and it

  1. Makes your test fail for each SEVERE error message logged in the console, printing the message.
  2. Display a warning for each javascript warning raised in the console.

Here is a real-world example of the output of a system test I had already in place for the homepage:

WARN: javascript warning
http://127.0.0.1:60979/assets/application.js 9457 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Got 3 failures and 1 other error from failure aggregation block "javascript errrors":1) http://127.0.0.1:60481/sso 10:18 Uncaught SyntaxError: Unexpected token ;

👏 Nice! Our test is failing because of the JS error and is also printing me a warning about another issue.

After running the whole suite of my system tests I could catch more errors and warnings and easily fix all of them.

Hope you find this helpful!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store