ewo*_*wok 5 javascript mocha.js node.js chai chai-as-promised
使用Mocha和chai-as-promised,我试图测试我的承诺是否得到正确解决和拒绝。但是expect由 chai-as-promised 提供的功能并没有正确地导致测试失败。例子:
测试.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
})
})
Run Code Online (Sandbox Code Playgroud)
当我执行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)
Run Code Online (Sandbox Code Playgroud)
您可以看到断言错误似乎被抛出,但 mocha 没有发现它们。我怎样才能让摩卡识别失败?
正如我们所确认的,为了将来参考,问题是您没有在每个测试中返回断言。
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
})
Run Code Online (Sandbox Code Playgroud)
这就是为什么测试通过了,但后来在它最终返回时打印了一个“未处理”的承诺。该return/拒绝关键字运筹学与摩卡等待异步功能来解决。
| 归档时间: |
|
| 查看次数: |
4646 次 |
| 最近记录: |