我读了the document chai.should()和chai.expect()应该以相同的方式工作,但是当我试图捕捉错误时,它似乎有所不同。正如我的理解,我可以使用should()来声明承诺链为
myfunction.should.be.rejectedWith(Error)
但是,由于函数会在promise链之前抛出错误,错误不会进入promise链,我不能使用这个方法。然后我使用如下方法。
如您所见,
() => myFunctionA(name).should.throw('argument name is undefine');
和
expect(() => myFunctionA(name).to.throw('Argument "stackName" is undefined');
根据文档,它们应该具有相同的效果,或者以相同的方式工作,但是,前者总是会通过,即使我从源代码中删除了错误。它无论如何都会通过。只有后者才能正常工作。有人知道为什么吗?你有更好的想法测试这样的“投掷错误”吗?
function myFunctionA(name) {
if (!name) {
throw new Error('argument name is undefine')
}
return Promise.resolve();
}
it.only('should throw Error if name is null|undefined ', () => {
let name;
() => myFunctionA(name).should.throw('argument name is undefine'); //this would pass no matter how
() => myFunctionA(name).should.Throw('argument name is undefine'); //this would pass no matter how
expect(() => myFunctionA(name).to.throw('Argument "stackName" is undefined'); // this will do the assert properly, this is work
return myFunctionA(name).should.throw(Error);// this will failed to catch the Error
});
答案 0 :(得分:0)
所以前两种情况:
() => myFunctionA(name).should.throw('argument name is undefine'); //this would pass no matter how
() => myFunctionA(name).should.Throw('argument name is undefine'); //this would pass no matter how
您正在创建一个永远不会被调用的匿名函数() => myFunctionA(name)
,因此您实际上并未调用myFunctionA
对于最后一个案例
myFunctionA(name).should.throw(Error);// this will failed to catch the Error
这不起作用,因为您的代码在.should
可以运行之前抛出错误。从文档[here] [1]中你应该像在3个案例中那样使用它。