Typescript Mocha Chai-As-Promised: how to test a function that can throw OR return a Promise

223 Views Asked by At

I'm testing a function to make sure it throws in certain situations. If the func doesn't throw it returns a Promise. For example:

function foo() {
  if ( true )
    throw new Error()

  return Promise.resolve()
}

describe( "", () => {
  it( "should throw", () => {
    foo.should.throw
  })
})

Works great except, if the func doesn't throw and instead returns a Promise, the test still passes. Which has got me confused how my code will behave if it does/doesn't throw, and how to properly handle this.

I could switch it to an async function to force a Promise return, but then I end up with an async func with no awaits: bad.

Am I supposed to return a Promise.reject? Does that mean I should never throw within a function that returns a Promise? Ex:

function foo() {
  if ( true )
    return Promise.reject( new Error() )

  return Promise.resolve()
}

describe( "", () => {
  it( "should throw", async () => {
    foo().should.eventually.be.rejected
  })
})

If that's the case then I have a ton of throws I need to convert to rejects. Thanks for your help and guidance on this!

0

There are 0 best solutions below