Rodrigo Rosenfeld Rosas

Testing JavaScript with Node.js, Jasmine and Sinon.js

Wed, 05 Oct 2011 23:22:00 +0000 (Updated at Thu, 03 Nov 2011 13:27:00 +0000)

For some years now, I've been writing lots of JavaScript. Not that I chose to, but it is the only available language for client-side programming. Well, not really since there are some languages that will compile to JavaScript. So, I chose to work with CoffeeScript lately, since it is far better than JavaScript for my tastes.

All this client-side programming requires testing too. While sometimes testing using real browsers suits better, tools like Selenium are extremely slow if you have tons of JavaScript to test. So, I was looking for a faster alternative that allowed me to test my client-side code.

Before I present the approach I decided to take, I'd like to warn you that there are lots of good alternatives out there. If you want to take a look at how to use the excellent PhantomJS headless webkit browser, you might be interested in this article.

I decided to go with a solution based on Node.js, a fast runtime JavaScript environment built on top of Google's V8 engine. Even using Node.js, you'll find out many good alternatives like Zombie.js, which can also be integrated to the excellent integration test framework Capybara through capybara-zombie. It can also be integrated to Jasmine through zombie-jasmine-spike.

Even though there are great options out there, I still chose another approach for no special reason. The interesting thing about Node.js, is that there's an interesting ecosystem behind it with tools like NPM which is a package manager for Node, similar to apt on Debian, for instance. On Debian, it can be installed with:

1
apt-get install -y node npm

But I would recommend installing just node through apt, and install npm using the instructions here:

1
curl http://npmjs.org/install.sh | sh

The reason for that is that the search command of the npm command provided by the Debian package was not working for me, running the list command instead. Maybe this happens only in the unstable distribution, but I don't want to get out of the main subject here.

Since we want to test our client-side script, it is necessary to install some library to emulate the browsers DOM, since Node won't provide one itself. The jsdom library seems to be the de facto standard one for creating a DOM environment.

I don't really like to read assertions, prefering expectations instead. If you're like me, you'll like the Jasmine.js library for writing your expectations in JavaScript. If you don't want to write integration tests, chances are that you'll need to mock your AJAX calls. Sinon.js is an excellent framework that will allow you to do that. And since I avoid JavaScript itself at all cost, I'll write all my examples using CoffeeScript.

If your web framework, differently from Rails doesn't support CoffeeScript by default, and still you got an interest on this language, you can use Jitter to watch your CoffeeScript files and convert them to JavaScript on the fly. It will replicate your directory structure, converting all your .coffee files to .js:

1
jitter src/coffee/ web-app/js/

Install all those dependencies with NPM:

1
npm install jitter jasmine-node jsdom

Although you can install jQuery and Sinon.js with 'npm install jquery sinon', that won't make sense, since you'll want to load them from your DOM environment. So download Sinon.js to your hard-disk to get faster tests.

I don't practice TDD (or BDD) and I this is a conscious choice. I find it faster to write the implementation first and then write the tests. So, proceeding with this approach, let me show you an example for a "Terms and Conditions" page. Here's a possible implementation (I'm showing only the client-side part):

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/jquery.ui.css">
    <script type="text/javascript" src="js/jquery-ui.min.js"></script>
    <script type="text/javascript" src="js/wmd/showdown.js"></script>
    <script type="text/javascript" src="js/show-terms-and-conditions.js"></script>
  </head>
  <body>
  </body>
</html>

Showdown is a JS library for converting Markdown to HTML. Here is the show-terms-and-conditions.coffee equivalent in CoffeeScript:


            
$ ->
  converter = new Attacklab.showdown.converter()
  lastTermsAndConditions = {}
  $.get 'termsAndConditions/lastTermsAndConditions', (data) ->
    lastTermsAndConditions = data
    $('<div/>').html(converter.makeHtml(lastTermsAndConditions.termsAndConditions))
      .dialog
        width: 800, height: 600, modal: true, buttons:
          'I agree': onAgreement, 'Log out': onLogout

  onAgreement = ->
    $.post 'termsAndConditions/agree', id: lastTermsAndConditions.id, =>
      $(this).dialog('close')
      window.location = '../' # redirect to home

  onLogout = ->
    $(this).dialog('close')
    window.location = '../logout' # sign out

As you can see, this will issue an AJAX request as soon as the page is loaded. So, we need to fake the AJAX call before we run show-terms-and-conditions.js. This can be easily done with this fake-ajax.js, using Sinon.js:

1
sinon.stub($, 'ajax')

If you're not using jQuery, you can try the "sinon.useFakeXMLHttpRequest()" documented in the "Fake XHR" example in Sinon.js site.

Ok, so here is a possible example of specification for this code in CoffeeScript. Jasmine-sinon can help you to write better expectations, so download it to 'spec/js/jasmine-sinon.js'.


            
# spec/js/show-terms-and-conditions.spec.coffee:

require './jasmine-sinon' # wouldn't you love if vanilla JavaScript also supported 'require'?
dom = require 'jsdom'

#f = (fn) -> __dirname + '/../../web-app/js/' + fn # if you prefer to be more explicit
f = (fn) -> '../../web-app/js/' + fn

window = $ = null

dom.env
  html: '<body></body>' # or require('fs').readFileSync("#{__dirname}/spec/fixures/any.html").toString()
  scripts: ['sinon.js', f('jquery/jquery.min.js'), f('jquery/jquery-ui.min.js'), f('wmd/showdown.js'), 'ajax-faker.js',
    f('showTermsAndConditions.js')]
  # src: ["console.log('all scripts were loaded')", "var loaded=true"]
  done: (errors, _window) ->
    console.log("errors:", errors) if errors
    window = _window
    $ = window.$
    # jasmine.asyncSpecDone() if window.loaded

# We must tell Jasmine to wait until the DOM is loaded and the script is run
# Jasmine doesn't support a beforeAll, like RSpec
beforeEach(-> waitsFor -> $) unless $
# another approach: (you should uncomment the line above for it to work)
# already_run = false
# beforeEach -> already_run ||= jasmine.asyncSpecWait() or true

describe 'showing Terms and Conditions', ->

  it 'should get last Terms and Conditions', ->
    @after -> $.ajax.restore() # undo the stubbed ajax call introduced by fake-ajax.js after this example.
    expect($.ajax).toHaveBeenCalledOnce()
    firstAjaxCallArgs = $.ajax.getCall(0).args[0]
    expect(firstAjaxCallArgs.url).toEqual 'termsAndConditions/lastTermsAndConditions'
    firstAjaxCallArgs.success id: 1, termsAndConditions: '# title'

  describe 'after set-up', ->
    beforeEach -> window.sinon.stub $, 'ajax'
    afterEach -> $.ajax.restore()
    afterEach -> $('.ui-dialog').dialog 'open' # it is usually closed at the end of each example

    it 'should convert markdown to HTML', -> expect($('h1').text()).toEqual 'title'

    it 'should close the dialog, send a request to server and redirect to ../ when the terms are accepted', ->
      $('button:contains(I agree)').click()
      ajaxRequestArgs = $.ajax.args[0][0]
      expect(ajaxRequestArgs.url).toEqual 'termsAndConditions/agree'
      expect(ajaxRequestArgs.data).toEqual id: 1

      ajaxRequestArgs.success()
      expect(window.location).toEqual '../'
      expect($('.ui-dialog:visible').length).toEqual 0

    it 'should close the dialog and redirect to ../logout when the terms are not accepted', ->
      # the page wasn't really redirected in this simulation by the prior example
      $('button:contains(Log out)').click()
      expect(window.location).toEqual '../logout'
      expect($('.ui-dialog:visible').length).toEqual 0

You can run this spec with:

1
jasmine-node --coffee spec/js/

The output should be something like:

1
2
3
4
5
Started
....

Finished in 0.174 seconds
2 tests, 9 assertions, 0 failures

Instead of writing "expect($('.ui-dialog:visible').length).toEqual 0", BDD would advice you to write "expect($('.ui-dialog')).toBeVisible()" instead. Jasmine allows you to write custom matchers. Take a look at my jQuery matchers for an example.

Unfortunately, due to a bug in jsdom, the expected implementations of toBeVisible and toBeHidden won't work for my cases, where I usually do that by toggling the hidden CSS class (.hidden {display: none}) of my elements. So, I check for this CSS class on my jQuery matchers.

Anyway, I'm just starting to write tests this way. Maybe there are better ways of writing tests like those.

Finally, if you want, you can also set up some auto-testing environment using a tool such as Guard that will watch your JavaScript (or CoffeeScript) files for changes and call jasmine-node on them. Here is an example Guardfile:

1
2
3
4
guard 'jasmine-node', jasmine_node_bin: File.expand_path("#{ENV['HOME']}/node_modules/jasmine-node/bin/jasmine-node") do
  watch(%r{^(spec/js/[^\.].+\.spec\.coffee)}) { |m| m[1] }
  watch('spec/js/jasmine-sinon.js'){ 'spec/js/' }
end

If you have any tips, please leave a comment.

Enjoy!

comments powered byDisqus