使用Mocha和chai-as-promised,我试图测试我的承诺正在被解决并被正确拒绝 . 但是chai-as-promised给出的 expect
函数没有正确地导致测试失败 . 例:
test.js
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
时:
foo
✓ resolve expected
✓ resolve unexpected
(node:2659) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected promise to be rejected but it was fulfilled with undefined
(node:2659) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
✓ reject expected
✓ reject unexpected
(node:2659) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): AssertionError: expected promise to be fulfilled but it was rejected with undefined
4 passing (10ms)
您可以看到断言错误似乎被抛出,但摩卡不会接受它们 . 如何让摩卡识别失败?
2 回答
正如我们确认的那样,并且为了将来参考,问题是您没有在每个测试中返回断言 .
这就是为什么测试通过但后来在最终返回时打印了"unhandled"的承诺 .
return
关键字通知mocha等待异步函数解析/拒绝 .或者使用chai-as-promise库,你可以尝试使用chai.should并调用.notify来表示它的“完成” . 像这样:
这样mocha将识别测试失败:
检查chai-as-promised doc以获取进一步的参考here