最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AsyncAwait throw an error in Mocha - Stack Overflow

programmeradmin1浏览0评论

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/);
});
发布评论

评论列表(0)

  1. 暂无评论