4

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Jeremy Trpka
  • 322
  • 1
  • 4
  • 20

2 Answers2

2

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)
Lin Du
  • 88,126
  • 95
  • 281
  • 483
-1

In Node JS sins v10.0.0 there is:

assert.rejects(asyncFn[, error][, message])

that works to check exceptions in async functions,

with Mocha it will looks like this:

it('should tests some thing..', async function () {
  await assert.rejects(async () => {
    throw new Error('This is an error')
  }, 'Error: This is an error')
})
user3531155
  • 439
  • 4
  • 11