为什么以下代码因超时而失败?它看起来像'应该'抛出一个错误,并且完成()永远不会被调用?如何编写此测试以使其正确失败而不是让jasmine报告超时?
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)测试应该工作 信息: 超时:5000毫秒等待规格完成后超时
答案 0 :(得分:4)
.then()
且仅使用done()
it('should work', (done) => {
Promise.resolve(3).then((num) => {
// your assertions here
}).catch((err) => {
expect(err).toBeFalsy();
}).then(done);
});
.then()
和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
以及上述示例的内容,但也有其他模块可让您直接从测试中返回承诺,而不是调用done()
和{{1 } - 见:
答案 1 :(得分:2)
如果您想在Promises
套件中使用Mocha
,则必须return
而不是使用done()
回调,例如:
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);