var gulp = require('gulp');
var spawn = require('child_process').spawn;
var mocha = require('gulp-mocha');
var log = require('fancy-log');

var node;
var paths = {
  srcJs: './src/**/*.js',
  srcUnit: './src/**/*Spec.js',
  srcIntegration: './tests/**/*.js'
};

gulp.task('src', function() {
  if (node){
    node.kill();
  }
  node = spawn('node', ['./src/app.js'], {stdio: 'inherit'});
  node.on('close', function (code) {
    if (code === 8) {
      gulp.log('Error detected, waiting for changes...');
    }
  });
});

gulp.task('env:dev', function(done) {
  process.env.PORT = 3000;
  process.env.NODE_ENV = 'development';
  done();
});

gulp.task('env:test', function(done) {
  process.env.PORT = 3001;
  process.env.NODE_ENV = 'test';
  done();
});


gulp.task('env:prod', function(done) {
  process.env.NODE_ENV = 'production';
  done();
});

gulp.task('serve', gulp.series(['env:dev', 'src'], function() {
  return gulp.watch([paths.srcJs], ['src']);
}));

gulp.task('test:unit', gulp.series(['env:test'], function() {
  return gulp.src([paths.srcUnit])
    .pipe(mocha())
    .on('error', log);
}));

gulp.task('test:api', gulp.series(['env:test'], function() {
  return gulp.src([paths.srcIntegration])
    .pipe(mocha());
}));

gulp.task('test:unit:watch', gulp.series(['test:unit'], function() {
  return gulp.watch([paths.srcUnit, paths.srcJs], ['test:unit']);
}));

gulp.task('test:api:watch', gulp.series(['test:api'], function() {
  return gulp.watch([paths.srcIntegration, paths.srcJs], ['test:api']);
}));

gulp.task('default', gulp.series(['serve']));

process.on('exit', function() {
  if (node) {
    node.kill();
  }
});

@@ -946,16 +946,28 @@
 s%5D, 
+gulp.series(
 %5B'src'%5D)
 ;%0A%7D)
@@ -962,16 +962,17 @@
 %5B'src'%5D)
+)
 ;%0A%7D));%0A%0A
@@ -1235,16 +1235,30 @@
 e(mocha(
+%7B exit: true %7D
 ));%0A%7D));
@@ -1374,24 +1374,36 @@
 ths.srcJs%5D, 
+gulp.series(
 %5B'test:unit'
@@ -1404,16 +1404,17 @@
 :unit'%5D)
+)
 ;%0A%7D));%0A%0A
@@ -1537,16 +1537,28 @@
 srcJs%5D, 
+gulp.series(
 %5B'test:a
@@ -1562,16 +1562,17 @@
 t:api'%5D)
+)
 ;%0A%7D));%0A%0A

Fix gulpfile issues with watchers and tests not exiting