Using Grunt and Jasmine with AMD

by Andy Appleton

Since yesterday’s post on running Jasmine specs with Grunt I have been working to integrate with a project which uses RequireJS. The Grunt Jasmine runner task I am using does not support AMD specs so I have created a fork which is available on GitHub.

To use it you will need to specify the repo URL in your package.json file…

"dependencies": {
  "grunt-jasmine-runner": "git://github.com/mrappleton/grunt-jasmine-runner.git"
}

If the amd flag is set in the grunt.js config file specs will be loaded via an AMD require call. This does not make an assumption about the AMD library being used, you must specify the path to that in the helpers option. Here’s a full example gruntfile:

module.exports = function(grunt) {
  grunt.initConfig({
    jasmine : {
      amd: true,
      // Your Jasmine spec files
      specs : 'specs/**/*spec.js',
      // Your spec helper files
      helpers: [
        '/path/to/require.js',
        '/path/to/requireConfig.js'
      ],
    }
  });

  // Register tasks.
  grunt.loadNpmTasks('grunt-jasmine-runner');

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

This assumes that your spec files are AMD modules which require the source files as necessary, e.g.

define(['/src/myModule.js'], function(MyModule){
  describe('MyModule', function(){
    // etc...
  });
});

The spec runner HTML file will then require each spec file in turn and execute the contents.

Summary

This is not the most flexible implementation, but it works for my use case and I think is worth releasing. I opened a pull request on the main repo which was (quite reasonably) declined as they are apparently already working on AMD support.

I’ll most probably switch back to the original version once AMD support arrives but for now this fork will do nicely for me and I hope it can be useful to others.