Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching gulp-mocha errors

I may be missing something extremely obvious but I can't get gulp-mocha to catch errors, causing my gulp watch task to end everytime I have a failing test.

It's a very simple set up:

gulp.task("watch", ["build"], function () {
  gulp.watch([paths.scripts, paths.tests], ["test"]);
});

gulp.task("test", function() {
  return gulp.src(paths.tests)
    .pipe(mocha({ reporter: "spec" }).on("error", gutil.log));
});

Alternatively, putting the handler on the entire stream also gives the same problem:

gulp.task("test", function() {
  return gulp.src(paths.tests)
    .pipe(mocha({ reporter: "spec" }))
    .on("error", gutil.log);
});

I've also tried using plumber, combine and gulp-batch to no avail, so I guess I'm overlooking something trivial.

Gist: http://gist.github.com/RoyJacobs/b518ebac117e95ff1457

like image 312
Roy Jacobs Avatar asked Feb 06 '14 11:02

Roy Jacobs


2 Answers

You need to ignore 'error' and always emit 'end' to make 'gulp.watch' work.

function handleError(err) {
  console.log(err.toString());
  this.emit('end');
}

gulp.task("test", function() {
  return gulp.src(paths.tests)
    .pipe(mocha({ reporter: "spec" })
    .on("error", handleError));
});

This makes 'gulp test' to always return '0' which is problematic for Continuous Integration, but I think we have no choice at this time.

like image 57
Shuhei Kagawa Avatar answered Nov 20 '22 15:11

Shuhei Kagawa


Expanding on Shuhei Kagawa's answer..

emitting end will prevent gulp exiting due to the uncaught error being converted into an exception.

Set a watching var to track whether you are running test through watch, then exit or not depending on whether you are developing or running CI.

var watching = false;

function onError(err) {
  console.log(err.toString());
  if (watching) {
    this.emit('end');
  } else {
    // if you want to be really specific
    process.exit(1);
  }
}

gulp.task("test", function() {
  return gulp.src(paths.tests)
    .pipe(mocha({ reporter: "spec" }).on("error", onError));
});

gulp.task("watch", ["build"], function () {
  watching = true;
  gulp.watch([paths.tests], ["test"]);
});

This can then be used for development and CI

like image 25
abovethewater Avatar answered Nov 20 '22 15:11

abovethewater