1

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.

gCurran
  • 11
  • 2
  • 1
    Sounds more like you want https://github.com/xjamundx/eslint-plugin-promise ? – loganfsmyth Mar 05 '16 at 06:17
  • @loganfsmyth that sounds like the right answer, though watch out for false positives, as there's in theory nothing wrong with this attribute-pattern: `this.onready = this.foo().then(() => this.bar());` (even though it's been controversial at times). To OP, as for testing this runtime, your test will time out, that's about it AFAIK. – jib Mar 05 '16 at 14:13

1 Answers1

1

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

Troopers
  • 5,127
  • 1
  • 37
  • 64