【发布时间】:2018-06-01 01:02:28
【问题描述】:
使用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)
您可以看到断言错误似乎被抛出,但 mocha 没有拾取它们。如何让 mocha 识别失败?
【问题讨论】:
-
我认为您应该返回
expect电话。您是否尝试在每个测试中添加return关键字? -
我刚刚试了一下。有用。但是现在我想知道您是如何将多个
expect语句放入一个测试中的? -
我不确定,我有一段时间没有使用 chai-promise 库了。
-
您能否接受该解决方案,以便其他人更容易找到答案。另外,如果您回答第二个问题,请告诉我,我可以更新解决方案:)
标签: javascript node.js mocha.js chai chai-as-promised