我读到了chai.should()和chai.expect()应该以相同的方式工作的the document,但当我尝试捕获错误时,它似乎不同。根据我的理解,我可以使用chain ()将promise chain断言为
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
});
发布于 2018-06-08 15:33:49
因此,在前两种情况下:
() => 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
可以运行之前抛出错误。从这里的文档中,您应该像在3个案例中一样使用它。
https://stackoverflow.com/questions/50758412
复制相似问题