我如何正确地失败茉莉节点中的asynchronousunit testing

为什么下面的代码失败,超时? 它看起来像“应该”抛出一个错误,done()永远不会被调用? 我如何编写这个testing,以便它正确地失败,而不是茉莉花报告超时?

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

控制台输出是:

c:> jasmine-node spec \

未处理的拒绝AssertionError:预期3到等于4 …失败:1)testing应该工作消息:超时:超过5000毫秒后超时等待规范完成

如果你想在你的Mocha套件中使用Promises ,你必须return它,而不是使用done()callback,如:

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

一个更清洁的方式来写这将是与chai-as-promised模块:

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

只要确保正确要求并告诉chai使用它:

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

使用.then()和只done()

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

使用done.fail()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 .catch()

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

其他选项

您特别询问了关于jasmine-node的内容,以上就是上面的例子,但是也有其他模块让您直接从testing中返回promise,而不是调用done()done.fail() – 请参阅: