Testing module pattern javascript with Jasmine & Karma

Testing module pattern (http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) Javascript browser code using test runners / build systems such as grunt or gulp is difficult. They seem to expect modules to be declared as Node modules. This is annoying when you have client code that uses a module pattern syntax and do not wish to change the client code immediately. I struggled with a simple way to test some module pattern code in Jasmine with a test runner that could also watch my files. Karma (http://karma-runner.github.io/0.12/index.html) appears to do that.

Module pattern

var myModule = (function(mod){
// Module code
return mod;
})(myModule || {});

Karma provides a watcher that can watch some Jasmine tests and application code. As the files are loaded in a browser it allows code using the module pattern to be tested with an automatic watcher.

The documentation for Karma is on the site. Ffiles are loaded as <script> tags in the order that they are configured. E.g.

 // list of files / patterns to load in the browser
 files: [
 'app/libs/*.js',
 'app/scripts/*.js',
 'tests/specs/*.js'
 ],

 // list of files to exclude
 exclude: [
 ],

How it works

While there’s a lot more going on under the hood the basic premise is that without using require.js Karma serves up a page that lists the scripts it finds in the file configuration (in the order they are specified in the configuration) into the body of the page as <script> tags. This means if your scripts work in a browser they are very likely to work in Karma. Fire up the debug Karma window and view source to see what it is going on.

Yes. We could move to require.js and AMD but if you have older Javascript or other reasons to use the module pattern then Karma is a good fit.

It is also possible to run karma in gulp so you can build a fuller workflow.

Posted in Uncategorized

Leave a comment