简体   繁体   中英

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

Using .then() and only done()

it('should work', (done) => {
  Promise.resolve(3).then((num) => {
    // your assertions here
  }).catch((err) => {
    expect(err).toBeFalsy();
  }).then(done);
});

Using .then() and done.fail()

it('should work', (done) => {
  Promise.resolve(3).then((num) => {
    // your assertions here
  }).then(done).catch(done.fail);
});

Using Bluebird coroutines

it('should work', (done) => {
  Promise.coroutine(function *g() {
    let num = yield Promise.resolve(3);
    // your assertions here
  })().then(done).catch(done.fail);
});

Using async / await

it('should work', async (done) => {
  try {
    let num = await Promise.resolve(3);
    // your assertions here
    done();
  } catch (err) {
    done.fail(err);
  }
});

Using async / await with .catch()

it('should work', (done) => {
  (async () => {
    let num = await Promise.resolve(3);
    // your assertions here
    done();
  })().catch(done.fail);
});

Other options

You specifically asked about jasmine-node so that's what the above examples are about but there are also other modules that let you directly return promises from tests instead of calling done() and done.fail() - see:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM