Last Updated: February 25, 2016
·
1.115K
· manudwarf

SpecRunner for Jasmine+Require

I wanted to have jasmine tests for my code, but as I use Require, I had to deal with the fact that modules were loaded by Require AFTER Jasmine ran, so no test would pass.

Finally managed to fix the issue by following a couple of guidelines :

Extract require.config.js

I have some shims/paths for require and I wanted to keep DRY, so I extracted my Require config in a separate file and load it right after require.js :

requirejs.config({
    baseUrl: "some/path",
    paths: {
        'backbone':                 'lib/backbone',
        'jquery':                   'lib/jquery',
        'underscore':               'lib/underscore'
    },
    shim: {
        'backbone': {
            deps: ['jquery', 'underscore'],
            exports: 'Backbone'
        },
        'jquery': {
            exports: '$'
        },
        'underscore': {
            exports: '_'
        }
    }
});

Wrap spec files into modules

Also necessary, have each spec wrapped into a define() call :

define("truth_spec", [], function() {
    describe("truth", function truth_spec() {
        it("should be true", function() {
            expect(true).toBe(true);
        });
    });
});

Have a specrunner

And finally, specrunner.js, that will run modules where the name ends by "_spec" :

require(["underscore"], function(_) {
   var specs = _.filter(require.s.contexts._.registry, function(mod) {
       // trick to check if ends with "_spec"
       return mod.map.name.slice(-5) === "_spec";
   });

   specs = _.map(specs, function(mod) {
       return mod.map.name;
   });

   require(specs, function() {
       jasmine.getEnv().execute();
   });
});

Et voilà !