Rob Bailey Rob Bailey - 3 months ago 10
Node.js Question

Testing express with Mocha: a promise-based test will not run by itself?

I have two test files. When only test1.js is present, no tests run, and mocha reports "0 passing" tests. When test1.js and test2.js are present but both depend on a promise, then still no tests run and mocha still reports "0 passing". But when one of the tests is modified to not use a promise, mocha runs both tests and they succeed. What the heck? Here are my files:

index.js:

require('./server').then( function(server) {
server.listen(8080, function() {
console.log("Started server");
});
);


server.js:

var express = require('express');
var server = express();

module.exports = new Promise((function(resolve, reject) {
return resolve(server);
}));


test1.spec.js:

require('./server').then(function(server) {
describe('Test Suite #1', function () {
it('should run test #1', function testSomething(done) {
return done();
});
});
});


test2.spec.js (server.js used as promise, tests do not run):

require('./server').then(function(server) {
describe('Test Suite #2', function () {
it('should run test #2', function testSomethingElse(done) {
return done();
});
});
});


test2.spec.js (server.js not used as promise, both tests run):

var server = require('./server');
describe('Test Suite #2', function () {
it('should run test #2', function testSomethingElse(done) {
return done();
});
});


To run them, I just have nodejs, express, and mocha installed and run:

% mocha "*.spec.*"


I understand I'm not using the server variable in these examples, but of course the real tests need to return a promise because sometimes the server.js is accessing remote systems for config data. I could work around this, but any help in understanding what's happening here would be greatly appreciated!

Answer

You need to describe and define all your tests synchronous. Otherwise they aren't recognized by mocha. If you have some async setup to make, use the before or beforeEach functions:

describe('Test Suite #1', function () {
  var server;
  before(function(done){
    require('./server').then(aServer => {
      server = aServer;
      done();
    });
  });
  it('should run test #1', function testSomething(done) {
    return done();
  });
});