【问题标题】:Chai: throwing error on async/await when no parameter is passedChai:没有传递参数时在异步/等待上抛出错误
【发布时间】:2020-03-16 10:54:28
【问题描述】:

我正在尝试测试我的代码(Typescript),它应该在没有传递参数时抛出

getID(ID) { if(!ID){throw new Error('stop js')} ....}

it('should fail if no ID', async () => { 

    expect(async () =>  await myService.getID() ).to.throw("stop js");
})

根据文档,上面应该可以工作,但是当我运行测试时,我得到了

 1) myTest
   should fail if no groupId is passed:
 AssertionError: expected [Function] to throw an error

【问题讨论】:

  • 你试过expect(async () => await myService.getID() ).to.eventually.throw("stop js");吗?
  • TypeError: [Function] 不是 thenable。这就是我得到的

标签: javascript typescript unit-testing testing chai


【解决方案1】:

您正在根据 Promise 进行操作; async/await 也是 Promises 的语法糖。

当你运行这样的代码时:

it('should fail if no ID', () => { 
    expect(/* not async */ myService.getID()).to.throw("stop js");
});

...对getID 的调用将同步抛出错误。但是,当您运行这样的代码时:

it('should fail if no ID', async () => { 
    expect(async () =>  await myService.getID()).to.throw("stop js");
});

...对async 的调用会将Promise 传递给expect,这将异步被您的错误拒绝。

如Cimes中NineBerry所说,可以安装并使用库chai-as-promised对Promises进行操作:

return expect(async () => await myService.getID()).to.eventually.throw("stop js");
// or
return expect(async () => await myService.getID()).to.eventually.be.rejectedWith("stop js");

你要么需要returnexpect的结果,要么await它;否则你的测试不会等到expect的结果才判断是否成功。

【讨论】:

  • 我安装了 chai-as-promise 但我得到一个“错误:无效的 Chai 属性:最终”
  • 有了这个解决方案,我得到 TypeError: [Function] is not a thenable。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 2018-12-20
  • 2020-08-22
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多