Reputation: 197
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
Upvotes: 3
Views: 2283
Reputation: 111496
.then()
and only done()
it('should work', (done) => {
Promise.resolve(3).then((num) => {
// your assertions here
}).catch((err) => {
expect(err).toBeFalsy();
}).then(done);
});
.then()
and done.fail()
it('should work', (done) => {
Promise.resolve(3).then((num) => {
// your assertions here
}).then(done).catch(done.fail);
});
it('should work', (done) => {
Promise.coroutine(function *g() {
let num = yield Promise.resolve(3);
// your assertions here
})().then(done).catch(done.fail);
});
async
/await
it('should work', async (done) => {
try {
let num = await Promise.resolve(3);
// your assertions here
done();
} catch (err) {
done.fail(err);
}
});
async
/await
with .catch()
it('should work', (done) => {
(async () => {
let num = await Promise.resolve(3);
// your assertions here
done();
})().catch(done.fail);
});
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:
Upvotes: 5
Reputation: 7862
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);
Upvotes: 2