Catch Javascript errors in your system tests
How to make your tests fail in case of Javascript errors with capybara and chrome headless
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.
I deployed a bug
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.
Catch JS errors in system tests
“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
- Makes your test fail for each SEVERE error message logged in the console, printing the message.
- 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!