admin管理员组

文章数量:1317894

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

it('should throw an error when no user ID is provided', (done) => {
  expect(async () => {
    await Client.getUserRemendations(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

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

it('should throw an error when no user ID is provided', (done) => {
  expect(async () => {
    await Client.getUserRemendations(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
Share Improve this question edited Sep 9, 2016 at 12:45 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked Sep 9, 2016 at 12:24 MazzyMazzy 14.2k47 gold badges133 silver badges217 bronze badges 2
  • 1 Please don't edit solutions into the question, rather post an answer. – Bergi Commented Sep 9, 2016 at 12:46
  • Notice that the async/await here is totally useless. expect(() => SClient.getUserRemendations(null, {})) uses a function that returns a promise just as well. – Bergi Commented Sep 9, 2016 at 12:47
Add a ment  | 

1 Answer 1

Reset to default 9

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.getUserRemendations(null, {})).be.rejectedWith(/Missing/);
});

本文标签: javascriptAsyncAwait throw an error in MochaStack Overflow