Running Gulp with Karma in Angular 6

1.5k Views Asked by At

I'm trying to execute a gulp task to run Karma after upgrading to Angular 6. Following the example in the readme on gulp-karma,

var gulp = require('gulp');
var Server = require('karma').Server;

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

I see this error in the output:

Error: The '@angular-devkit/build-angular/plugins/karma' karma plugin is meant to be used from within Angular CLI and will not work correctly outside of it.

It seems like either gulp needs to run karma through angular-cli or the options and overrides provided to the task need to change.

I'm using:

  • "@angular/cli": "~6.0.8"
  • "karma": "^1.7.1"
  • "gulp-util": "^3.0.8"

Can someone please provide the correct initialization to make Karma test work in this scenario?

1

There are 1 best solutions below

0
On

The following will work given the updates to Angular 6. You will need to call child_process().exec to execute ng test. This will allow you to run tests within the angular-cli framework. It may also be necessary to supply additional arguments such as increasing the maxBuffer size to avoid the Error: stderr maxBuffer exceeded in the event the buffer overflows. If you are using this for CI, then you will also want to use Chrome's headless mode to avoid browser output.

gulpfile.js

var gulp = require('gulp');
var exec = require('child_process').exec;

gulp.task('default', function (cb) {
    let maxBuffer = 1000 * 1024    // The default is 200 * 1024
    let options = {
        maxBuffer: maxBuffer
    }

    exec('ng test --watch=false --browsers=ChromeHeadless', options, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
})

karma.conf.js - Headless mode

customLaunchers: {
  ...
  ChromeHeadless: {
    base: 'Chrome',
    flags: [
      '--headless',
      '--disable-gpu',
      '--remote-debugging-port=9222'
    ],
  }
}

Finally, there is an alternative which uses child_process.spawn() to call ng test instead of exec(). However, I was getting an error when the gulp-cli was installed globally and not locally. This should also allow you to also work around the maxBuffer exceeded error.