Testing (Angular) RequireJS Modules in Karma
If you’re writing RequireJS modules, figuring out how to test them under Karma can leave you scratching your head. Writing them for AngularJS adds an extra wrinkle. Luckily it only takes a little bit of extra work.
First, you’ll need to install the RequireJS adapter for Karma:
npm install --save-dev karma-requirejs
Next, create a RequireJS configuration (e.g. test/requirejs.conf.js
) for your testing setup. Note that this will be in addition to any other RequireJS configuration you already have — it is for testing only.
// This code builds the array of test files.
// In this example it collects filenames that match the *Spec.js pattern
// -- change it for your situation.
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec.js$/.test(file)) {
tests.push(file);
}
}
}
requirejs.config({
// Karma serves files from '/base'.
baseUrl: '/base',
// Tell Require.js to load the test files (*Spec.js).
deps: tests,
// Start the test run once RequireJS is done.
callback: window.__karma__.start
});
Then modify your Karma config (karma.conf.js
):
module.exports = function(config) {
config.set({
// Include the RequireJS adapter.
// This assumes you're using Jasmine as well.
frameworks: ['jasmine', 'requirejs'],
// Modify the "files" property so that *only* the RequireJS configs are included.
// This is accomplished by setting the "included" property on other files to false.
files: [
{ pattern: 'src/*.js', included: false }, // source files
{ pattern: 'test/*.js', included: false }, // test files
'src/requirejs.conf.js', // general RequireJS config (if applicable)
'test/requirejs.conf.js' // your test-specific config (see above)
]
});
};
Finally, each of your test files should be wrapped inside a RequireJS module with its dependencies:
// This says that your tests require the 'yourAppModule' and 'angular-mocks' modules.
// 'yourAppModule' is the module name used for your project. It is included because
// the tests rely on the project code.
// Our apps are written in Angular, so 'angular-mocks' is included for the ngMock stuff.
// (This module is just a reference to the angular-mocks.js file.)
define(['yourAppModule', 'angular-mocks'], function() {
// your tests go in here
});
Thanks goes to following info that helped me reach this solution:
- Testing AngularJS in a RequireJS Environment by Radius Engineering
- Karma docs on RequireJS
- ngBook
|