Search code examples
javascriptes6-promise

How to test a promise has a catch method defined?


I have a method that returns a promise.

doStuf() { 
  return somePromise
    .then(...)
    .catch(e => {...}) 
}

I want to write a test that makes sure the promise returned by the doStuff method has a catch method.

How to do that ?


Solution

  • That is not a useful thing to test. Consider that doStuf may be refactored later into something more multi-layered, where several then-catch chains may exist, or the implementation will change in some other ways.

    You don't actually want to test the implementation, because you can simply look at it to see whether the promise has a catch. No, you want to test the behaviour of doStuf. You want to assert that doStuf returns a promise, and that that promise returns the expected value given certain input. E.g.:

    doStuf('foo').then(r => /* assert r equals expected outcome */)
    doStuf('bar').catch(r => /* assert r equals expected error */)