简体   繁体   中英

Test Promise chain ends in .catch (using Mocha / Chai as promised)

I've seen lots of info on testing Promise rejections, but wondering if anyone knows how to write a test that will fail if a promise chain doesn't end with a '.catch'? I'm trying to protect against swallowed errors.

For example, this would pass the test:

doSomething()                            // returns a Promise
.then(doSomethingElse)                   // returns a Promise
.then(handleResult)
.catch((err) => { console.log(err); });  // logs errors from any rejections

And this would fail:

doSomething()                            // returns a Promise
.then(doSomethingElse)                   // returns a Promise
.then(handleResult);                     // no catch = swallowed errors

I'm using mocha and chai-as-promised. I'm not using any promise libraries, just native es2015.

You need return the promise and test it is rejected with chai-as-promised

In should style :

return doSomething()                            
.then(doSomethingElse)                   
.then(handleResult).should.be.rejectedWith(Error);  

or

return doSomething()                            
.then(doSomethingElse)                   
.then(handleResult).should.be.rejected; 

return is important

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM