Verify that an exception is thrown using Mocha / Chai and async/await

后端 未结 11 883
花落未央
花落未央 2020-12-14 05:50

I\'m struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await.

Here\'s an example that works, but I dislike t

11条回答
  •  太阳男子
    2020-12-14 06:52

    A no dependency on anything but Mocha example.

    Throw a known error, catch all errors, and only rethrow the known one.

      it('should throw an error', async () => {
        try {
          await myFunction()
          throw new Error('Expected error')
        } catch (e) {
          if (e.message && e.message === 'Expected error') throw e
        }
      })
    

    If you test for errors often, wrap the code in a custom it function.

    function itThrows(message, handler) {
      it(message, async () => {
        try {
          await handler()
          throw new Error('Expected error')
        } catch (e) {
          if (e.message && e.message === 'Expected error') throw e
        }
      })
    }
    

    Then use it like this:

      itThrows('should throw an error', async () => {
        await myFunction()
      })
    

提交回复
热议问题