Search code examples
node.jsjasmine-node

How do I properly fail an async unit test in jasmine-node


Why does the following code fail with a timeout? It looks like 'should' throws an error and done() never gets called? How do I write this test so that it fails correctly instead of having jasmine reporting a timeout?

var Promise = require('bluebird');
var should = require('chai').should();
describe('test', function () {
  it('should work', function (done) {
    Promise.resolve(3)
      .then(function (num) {
        num.should.equal(4);
        done();
      });
  });
});

console output is:

c:>jasmine-node spec\

Unhandled rejection AssertionError: expected 3 to equal 4 ... Failures: 1) test should work Message: timeout: timed out after 5000 msec waiting for spec to complete


Solution

  • If you want to use Promises in your Mocha suite, you have to return it instead of using the done() callback, like:

    describe('test', function () {
      it('should work', function () {
        return Promise.resolve(3)
          .then(function (num) {
            num.should.equal(4);
          });
      });
    });
    

    An even cleaner way to write that would be with chai-as-promised module:

    describe('test', function () {
      it('should work', function () {
        return Promise.resolve(3).should.eventually.equal(4);
      });
    });
    

    Just make sure to require it properly and tell chai to use it:

    var Promise = require('bluebird');
    var chai = require('chai');
    var should = chai.should();
    var chaiAsPromised = require('chai-as-promised');
    
    chai.use(chaiAsPromised);