Reputation: 374
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?
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.
Upvotes: 5
Views: 2989
Reputation: 439
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')
})
Upvotes: -1
Reputation: 102207
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)
Upvotes: 3