Bendangelo Blog

Simple Karma Task for Gulp

Nov 14, 2015 1 minute read

The other day I could not find an acceptable Karma task for Gulp, so I spent some time on my own. Using Karma ~1.3.0 and Gulp ~3.9.0.

/**
* Run test once and exit
*/
gulp.task('test', function (done) {
var karmaServer = new karma.Server({
configFile: __dirname + '/test/karma.conf.js',
singleRun: true
}, function (exitCode) {
done();
process.exit(exitCode);
}).start();
});
/**
* Run tests in chrome browser
*/
gulp.task('test:chrome', function (done) {
var karmaServer = new karma.Server({
configFile: __dirname + '/test/karma.conf.js',
browsers: ['Chrome']
}, function (exitCode) {
done();
process.exit(exitCode);
}).start();
});
/**
* Watch for file changes and re-run tests on each change
*/
gulp.task('tdd', function (done) {
var karmaServer = new karma.Server({
configFile: __dirname + '/test/karma.conf.js'
}, function () {
done();
}).start();
});
view raw GulpFile.js hosted with ❤ by GitHub

process.exit will stop the task, preventing weird error messages from Gulp. I think Karma calls the complete method for each test file? I don’t know, either way it makes the two dance well together.

One more thing, just a warning do not refactor the last task to match.

var karmaServer = new karma.Server({
    configFile: __dirname + '/test/karma.conf.js'
}, done).start();

There is an integration problem where Gulp will try to read the arguments sent into the done() method. More about this pestering issue here.

Related Posts