Search code examples
node.jsasync-awaitmocha.jsbddchai

Mocha - Assert asynchronous function throws exception


I am trying to test if an async function is going to throw an exception, but I keep getting this error:

AssertionError: expected [Function] to throw an error

I am using Mocha with Chai's assertion library.

it('Throw an error', async () => {
    assert.throws(async () => {
        await retrieveException();
    }, Error);

    const retrieveException = async () => {
        // code snippit
        throw new Error('This is an error');
    }
}

Is there something I am doing wrong with either checking for a thrown exception, the async nature, or both?

References

I have seen previous questions here (where the one answer goes through the three different libraries [assert and the two BDD methods]), and I was unable to get something to work.

This article doesn't help much either.

Nor the documentation article from Node.js.


Solution

  • expect().to.throw(Error) will only work for sync functions. If you want a similar feature using async functions take a look at chai-as-promised

    E.g.

    import chai, { assert } from 'chai';
    import chaiAsPromised from 'chai-as-promised';
    
    chai.use(chaiAsPromised);
    
    describe('63511399', () => {
      it('Throw an error', async () => {
        const retrieveException = async () => {
          throw new Error('This is an error');
        };
        return assert.isRejected(retrieveException(), Error);
      });
    });
    

    unit test result:

      63511399
        ✓ Throw an error
    
    
      1 passing (29ms)