Capybara: check that JavaScript works without errors

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

I know that I can add something to the DOM at the end of my JavaScript file and confirm the presence of this content, but it seems to hack and makes me pollute my code for testing. I would rather do something like that.

visit some_path page.should succesfully_run_javascript 
+7
ruby-on-rails capybara
source share
2 answers

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

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

The first line displays errors that are convenient for viewing what is happening. The second line causes the test to fail.

+4
source share

One way that is potentially not very polluting is to collect any errors by adding something like this to the head (remember that this will override any onerror handler that you already have):

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

Then you can do something like:

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

and state that the array is empty. You could print errors otherwise ...

Note. It is important to add a scriptlet to the head (possibly like the first scriptlet / script tag), since it must be one of the first scripts to be run.

+3
source share