Stop Gulp Build on Unit Test Failure

Submitted by Derrick on

I have been setting up an Ionic (http://ionicframework.com/) project using gulp, and the ionic templates don't include any unit tests. This would not do. First, I followed these posts to get unit testing set up with Karma and Jasmine:

But that still didn't get the gulp build to fail and exit upon unit test failures, as I would want for a nice Continuous Integration setup. After looking through a bunch of Gulp and Karma api docs and stack overflow posts, I came to this setup. It will exit the build if tests fail (though tasks still run in parallel to take advantage of the gulp paradigm) and it also adds the karma test watcher to the gulp watch task.

gulpfile.js

...

/**
* Test task, run test once and exit with error if failure
*/
gulp.task('test', function(done) {
    karma.start({
        configFile: __dirname + '/tests/karma.conf.js',
        singleRun: true
    }, function(code) {
        if (code == 1){
        console.log('Unit Test failures, exiting process');
           done('Unit Test Failures');
        } else {
            console.log('Unit Tests passed');
            done();
        }
    });
});

gulp.task('default', ['test', 'sass']);

gulp.task('sass', function(done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function() {
    gulp.watch(paths.sass, ['sass']);
    karma.start({
      configFile: __dirname + '/tests/karma.conf.js',
      singleRun: false
    });
});