Question

I have a set of gulp.js targets for running my mocha tests that work like a charm running through gulp-mocha. Question: how do I debug my mocha tests running through gulp? I would like to use something like node-inspector to set break points in my src and test files to see what's going on. I am already able to accomplish this by calling node directly:

node --debug-brk node_modules/gulp/bin/gulp.js test

But I'd prefer a gulp target that wraps this for me, e.g.:

gulp.task('test-debug', 'Run unit tests in debug mode', function (cb) {
   // todo?
});

Ideas? I want to avoid a bash script or some other separate file since I'm trying to create a reusable gulpfile with targets that are usable by someone who doesn't know gulp.

Here is my current gulpfile.js

// gulpfile.js
var gulp = require('gulp'),
  mocha = require('gulp-mocha'),
  gutil = require('gulp-util'),
  help = require('gulp-help');

help(gulp); // add help messages to targets

var exitCode = 0;

// kill process on failure
process.on('exit', function () {
  process.nextTick(function () {
    var msg = "gulp '" + gulp.seq + "' failed";
    console.log(gutil.colors.red(msg));
    process.exit(exitCode);
  });
});

function testErrorHandler(err) {
  gutil.beep();
  gutil.log(err.message);
  exitCode = 1;
}

gulp.task('test', 'Run unit tests and exit on failure', function () {
  return gulp.src('./lib/*/test/**/*.js')
    .pipe(mocha({
      reporter: 'dot'
    }))
    .on('error', function (err) {
      testErrorHandler(err);
      process.emit('exit');
    });
});

gulp.task('test-watch', 'Run unit tests', function (cb) {
  return gulp.src('./lib/*/test/**/*.js')
    .pipe(mocha({
      reporter: 'min',
      G: true
    }))
    .on('error', testErrorHandler);
});

gulp.task('watch', 'Watch files and run tests on change', function () {
  gulp.watch('./lib/**/*.js', ['test-watch']);
});
Was it helpful?

Solution

With some guidance from @BrianGlaz I came up with the following task. Ends up being rather simple. Plus it pipes all output to the parent's stdout so I don't have to handle stdout.on manually:

  // Run all unit tests in debug mode
  gulp.task('test-debug', function () {
    var spawn = require('child_process').spawn;
    spawn('node', [
      '--debug-brk',
      path.join(__dirname, 'node_modules/gulp/bin/gulp.js'),
      'test'
    ], { stdio: 'inherit' });
  });

OTHER TIPS

You can use Node's Child Process class to run command line commands from within a node app. In your case I would recommend childprocess.spawn(). It acts as an event emitter so you can subscribe to data to retrieve output from stdout. In terms of using this from within gulp, some work would probably need to be done to return a stream that could be piped to another gulp task.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top