I create gulp task for unit tests. I add nodemon for automatically run server then run test. But have error when run gulp task again. I have error that the port is already busy with another process.
I user this code:
var gulp = require('gulp'),
gulpUtil = require('gulp-util'),
gulpShell = require('gulp-shell'),
gulpEnv = require('gulp-env'),
gulpNodemon = require('gulp-nodemon'),
gulpMocha = require('gulp-mocha');
gulp.task('default', function () {
gulpUtil.log('unit - run unit tests');
});
gulp.task('server', function (callback) {
var started = false;
return gulpNodemon({
script: './build/app.js'
})
.on('start', function () {
if (!started) {
started = true;
return callback();
}
})
});
gulp.task('unit', ['server'], function () {
return gulp.src('./src/*.js')
.pipe(gulpMocha({reporter: 'spec'}))
.once('error', function () {
process.exit(1);
})
.once('end', function () {
process.exit();
})
});
How I can stop or kill server after unit tests?
Addition to answer: Now I have gulpfile.js:
var gulp = require('gulp'),
gulpUtil = require('gulp-util'),
gulpNodemon = require('gulp-nodemon'),
gulpMocha = require('gulp-mocha'),
gulpShell = require('gulp-shell');
var runSequence = require('run-sequence');
var nodemon;
gulp.task('default', function () {
gulpUtil.log('compile - compile server project');
gulpUtil.log('unit - run unit tests');
});
gulp.task('compile', function () {
return gulp.src('./app/main.ts')
.pipe(gulpShell([
'webpack'
]))
});
gulp.task('server', function (callback) {
nodemon = gulpNodemon({
script: './build/app.js'
})
.on('start', function () {
return callback();
})
.on('quit', function () {
})
.on('exit', function () {
process.exit();
});
return nodemon;
});
gulp.task('test', function () {
return gulp.src('./src/*.js')
.pipe(gulpMocha({reporter: 'spec'}))
.once('error', function () {
nodemon.emit('quit');
})
.once('end', function () {
nodemon.emit('quit');
});
});
gulp.task('unit', function() {
runSequence('compile', 'server', 'test');
});
Also in my server script I add this snippet:
this.appListener = this.http.listen(process.env.PORT || 3000, '0.0.0.0', function() {
console.log(chalk.green("Server started with port " + _this.appListener.address().port));
});
// **Add**
function stopServer() {
console.log(chalk.cyan('Stop server'));
process.exit();
}
process.on('exit', stopServer.bind(this));
process.on('SIGINT', stopServer.bind(this));
So, when test finished and I call process.exit()
in server script I add event exit event handler that stop server and gulp task successfully finished with stopped server.
Nodemon has a quit
command. Have a look at Using nodemon events and concerning your module also its docs. According to the documentation you could use:
var nodemon = require('nodemon');
// force a quit
nodemon.emit('quit');