我正在尝试测试我的代码(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
您正在使用Promises;async
/await
也是Promises的句法糖。
当你运行这样的代码时:
it('should fail if no ID', () => {
expect(/* not async */ myService.getID()).to.throw("stop js");
});
对CCD_ 3的调用将同步地抛出错误。然而,当你运行这样的代码时:
it('should fail if no ID', async () => {
expect(async () => await myService.getID()).to.throw("stop js");
});
对async
的调用将向expect
传递一个Promise,该Promise将异步地被您的Error拒绝。
正如NineBerry在评论中提到的,你可以按照承诺安装和使用库chai,在Promise:上运行
return expect(async () => await myService.getID()).to.eventually.throw("stop js");
// or
return expect(async () => await myService.getID()).to.eventually.be.rejectedWith("stop js");
您需要return
expect
的结果,或者await
;否则,您的测试将不会在确定是否成功之前等待expect
结果。