测试承诺链以.catch结尾(使用Mocha/Chai承诺)
问题描述:
我已经看到很多关于测试Promise拒绝的信息,但是想知道是否有人知道如何编写测试,如果承诺链不会失败以'.catch'结尾?我试图防止吞下的错误。测试承诺链以.catch结尾(使用Mocha/Chai承诺)
例如,这将通过测试:
doSomething() // returns a Promise
.then(doSomethingElse) // returns a Promise
.then(handleResult)
.catch((err) => { console.log(err); }); // logs errors from any rejections
,这将失败:
doSomething() // returns a Promise
.then(doSomethingElse) // returns a Promise
.then(handleResult); // no catch = swallowed errors
我使用摩卡和柴作为-承诺。 我没有使用任何承诺库,只是原生es2015。
答
你需要回报的承诺,并测试它被拒绝,柴作为许诺的
应当风格:
return doSomething()
.then(doSomethingElse)
.then(handleResult).should.be.rejectedWith(Error);
或
return doSomething()
.then(doSomethingElse)
.then(handleResult).should.be.rejected;
return
是重要
声音更喜欢你想要https://github.com/xjamundx/eslint-plugin-promise? – loganfsmyth
@loganfsmyth这听起来像是正确的答案,但要注意误报,因为理论上这个属性模式没有错:this.onready = this.foo()。then(()=> this.bar( ));'(尽管它有时是有争议的)。对于OP,至于测试这个运行时,你的测试会超时,就是AFAIK。 – jib