Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara: Test that JavaScript runs without errors

I would like to write a request spec that verifies the loading and execution of javascript on a given page without any errors.

I know I can add something to the DOM at the end of my JavaScript file and assert the presence of this content, but that feels like a hack and forces me to pollute my code for testing reasons. I'd prefer to do something along the lines of.

visit some_path
page.should succesfully_run_javascript
like image 271
Niels B. Avatar asked Jul 24 '13 13:07

Niels B.


People also ask

Does capybara run JavaScript?

By default Capybara uses Rack::Test which is a headless browser emulator. It gives us great speed, but we sacrifice the ability to run JavaScript. If you need to test JS as part of your integration suite, then you need to use another driver.

What is Capybara testing?

Capybara is a web-based test automation software that simulates scenarios for user stories and automates web application testing for behavior-driven software development. It is written in the Ruby programming language.


2 Answers

You can achieve this with the following piece of code in your tests.

page.driver.console_messages.each { |error| puts error }
expect(page.driver.console_messages.length).to eq(0)

The first line prints out an errors, handy for seeing what's going on. The second line causes the test to fail.

like image 53
Ian Purton Avatar answered Oct 19 '22 22:10

Ian Purton


One way that's potentially not very polluting is to collect any errors by adding something like this to head (keep in mind this will override any onerror handler you may already have):

<script>
    window.errors = [];
    window.onerror = function(error, url, line) {
        window.errors.push(error);
    };
</script>

You could then do something like:

page_errors = page.evaluate_script('window.errors')

and assert on the array being empty. You could output the errors otherwise...

Note: It's important to add the scriptlet to head (potentially as the first scriptlet/script tag) as it needs to be one the first executed scripts.

like image 33
Adrian CB Avatar answered Oct 20 '22 00:10

Adrian CB