Testing your JavaScript with Jasmine and Grunt

by Andy Appleton

I’ve written about clean modular JavaScript and a nice benefit of writing code that way is testability. Recently I’ve been using Jasmine to write JS unit tests having also played with Mocha and Qunit. Jasmine has a clean interface, runs specs inside an HTML page and I find the finished spec files extremely readable thanks to rspec style test nesting.

Jasmine example spec output

Jasmine’s HTML spec runner is great for writing and running tests locally, but it is not very practical for integrating into a CI server – for that we need a command line tool.


Grunt is a really cool build tool for JavaScript. By default it includes tasks for linting, concatenating & minifying and running Qunit tests in a headless Phantomjs instance. It has a nice collection of tasks available as modules on NPM including a few for running Jasmine specs.

To get up and running we need to install Grunt, Phantomjs and the Grunt Jasmine runner task from the command line (I’m assuming you have node and NPM installed):

$ cd /path/to/project
$ npm install grunt
$ npm install grunt-jasmine-runner

If you’re on a Mac and use Homebrew you can grab PhantomJS:

$ brew install phantomjs

For other platforms there are a number of pre built binaries available.

Now all we need to do is add the appropriate configuration to a grunt.js file in the project’s root…

module.exports = function(grunt) {
    jasmine : {
      // Your project's source files
      src : 'src/**/*.js',
      // Your Jasmine spec files
      specs : 'specs/**/*spec.js',
      // Your spec helper files
      helpers : 'specs/helpers/*.js'

  // Register tasks.

  // Default task.
  grunt.registerTask('default', 'jasmine');

…and run the tests!

$ grunt jasmine

Jasmine command line output