使用Mocha和chai-as-promised,我正在尝试测试我的承诺是否得到妥善解决和拒绝。但是chai-as-promise给出的 cron:
- description: "Lead Data Update"
url: /cronjobPrivate/processLeads
schedule: every 1 minutes
函数没有正确地导致测试失败。例如:
test.js
expect
执行const chai = require('chai')
chai.use(require('chai-as-promised'))
const expect = chai.expect
describe('foo', () => {
it('resolve expected', () => {
expect(new Promise((res,rej) => {res()})).to.be.fulfilled
})
it('resolve unexpected', () => {
expect(new Promise((res,rej) => {res()})).to.be.rejected
})
it('reject expected', () => {
expect(new Promise((res,rej) => {rej()})).to.be.rejected
})
it('reject unexpected', () => {
expect(new Promise((res,rej) => {rej()})).to.be.fulfilled
})
})
时:
mocha test.js
你可以看到断言错误似乎被抛出,但是mocha不会接受它们。如何让摩卡识别失败?
答案 0 :(得分:4)
正如我们确认的,以及将来的参考,问题是你没有在每次测试中返回断言。
it('reject expected', () => {
return expect(new Promise((res,rej) => {rej()})).to.be.rejected
})
it('reject unexpected', () => {
return expect(new Promise((res,rej) => {rej()})).to.be.fulfilled
})
这就是为什么测试通过但后来打印了一个"未处理的"当它最终回归时承诺。 return
关键字通知mocha等待异步函数解析/拒绝。
答案 1 :(得分:1)
或者使用chai-as-promised库,您可以尝试使用chai.should并调用.notify来指示其“已完成”。像这样:
const chai = require('chai');
chai.use(require('chai-as-promised'));
chai.should();
const expect = chai.expect;
describe('foo', () => {
it('resolve expected', () => {
expect(new Promise((res, rej) => { res(); })).to.be.fulfilled;
});
it('resolve unexpected', (done) => {
// expect(new Promise((res, rej) => { res(); })).to.be.rejected;
new Promise((res, rej) => { res(); }).should.be.rejected.and.notify(done);
});
it('reject expected', (done) => {
// expect(new Promise((res, rej) => { rej(); })).to.be.rejected;
new Promise((res, rej) => { rej(); }).should.be.rejected.and.notify(done);
});
it('reject unexpected', (done) => {
// expect(new Promise((res, rej) => { rej(); })).to.be.fulfilled;
new Promise((res, rej) => { rej(); }).should.be.fulfilled.and.notify(done);
});
});
这样mocha将识别测试失败:
foo
√ resolve expected
1) resolve unexpected
√ reject expected
2) reject unexpected
2 passing (37ms) 2 failing
1) foo
resolve unexpected:
AssertionError: expected promise to be rejected but it was fulfilled with undefined
2) foo
reject unexpected:
AssertionError: expected promise to be fulfilled but it was rejected with undefined
检查chai-as-promised doc以获取进一步参考here