How to verify that an exception is thrown using Mocha and Chai and async and await?

Sometimes, we want to verify that an exception is thrown using Mocha and Chai and async and await.

In this article, we’ll look at how to verify that an exception is thrown using Mocha and Chai and async and await.

How to verify that an exception is thrown using Mocha and Chai and async and await?

To verify that an exception is thrown using Mocha and Chai and async and await, we can use the chai-as-promised package.

We install it by running

npm i chai-as-promised

Then we can use it by writing

const chai = require('chai')
const {
  expect
} = chai
chai.use(require('chai-as-promised'))

const wins = async () => {
  return 'Winner'
}

const fails = async () => {
  throw new Error('Contrived Error')
}

it('wins() returns Winner', async () => {
  expect(await wins()).to.equal('Winner')
})

it('fails() throws Error', async () => {
  await expect(fails()).to.be.rejectedWith(Error)
})

We add the chai-as-promised plugin with

chai.use(require('chai-as-promised'))

Then we test the wins and fails async functions by calling it with an async function.

And we get the resolved value of wins with await and use equal to check it resolve value.

And we test for rejected promise from the fails function by call fails and then use rejectedWith with awit to check the error thrown.

Conclusion

To verify that an exception is thrown using Mocha and Chai and async and await, we can use the chai-as-promised package.