Marcel Marcel - 5 months ago 34
Node.js Question

npm run script: node server.js && mocha test

My use case is pretty simple:

First I want to run

node server.js
(start my Node.js app) - and after Node has started - I want to run
mocha test
(running some tests on the API provided by previous
) by executing
npm run test

The script:
"test": "NODE_ENV=development node server.js && mocha test"

Node starts, but unfortunately the
mocha test
does not seem to be executed:

enter image description here

So how can I execute
mocha test
node server.js


The reason why you're running into this is because node server.js continuously runs until killed (Ctrl + C) or a fatal unhandled exception occurs. Since the node process keeps running mocha test never get executed.

One approach to this would be to use gulp as a task runner and utilize tasks implementing gulp-nodemon and gulp-mocha. If you've never used Gulp before or are unfamiliar with task runners I suggest you read the docs beforehand just to get an idea of how it works.

Add the gulpfile.js below to your app (adjust some of the settings as necessary) and modify your package.json scripts with the test script below and this should solve your issue.


var gulp = require('gulp');
var mocha = require('gulp-mocha');
var nodemon = require('gulp-nodemon');

gulp.task('nodemon', (cb) => {
  let started = false;

  return nodemon({
    script: 'server.js'
    .on('start', () => {
      if (!started) {
        started = true;
        return cb();
    .on('restart', () => {


gulp.task('test', ['nodemon'], function() {
  return gulp.src('./test/*.js')
    .pipe(mocha({reporter: 'spec' }))  
    once('error', function() {
    .once('end', function() {

package.json scripts

  "scripts": {
    "test": "NODE_ENV=development gulp test"

Supertest Alternative

A more elegant solution ,and in my opinion the better option, would be to rewrite your tests to use supertest. Basically what you do with supertest is pass your Express instance to it and run assertions tests against it with the supertest package.

var mocha = require('mocha');
var request = require('supertest');
var server = require('server');

describe('test server.js', function() {

    it('test GET /', function(done) {
            .expect(200, done);