Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/Await throw an error in Mocha

I'm trying to catch an error which should be throw by the function getUserRecommendations. This is my example:

it('should throw an error when no user ID is provided', (done) => {
  expect(async () => {
    await Client.getUserRecommendations(null, {})
  }).to.throw(/Missing/)
})

Unfortunately it doesn't work and I get as result that my test it doesn't pass along with this message:

AssertionError: expected [Function] to throw an error
like image 895
Mazzy Avatar asked Jan 05 '23 09:01

Mazzy


1 Answers

The way you have set up the the test won't work because expect.to.throw is not expecting a promise. At least I think that is what is going on based on this issue.

The best alternative is to use chai-as-promised and do something like:

it('should throw an error when no user ID is provided', () => {
  expect(Client.getUserRecommendations(null, {})).be.rejectedWith(/Missing/);
});
like image 80
Davin Tryon Avatar answered Jan 13 '23 10:01

Davin Tryon