柴:是否期望错误取决于参数 [英] Chai: expecting an error or not depending on a parameter
问题描述
我一直在尝试编写处理错误的函数的文本,如果该错误是有效错误,则抛出该错误,但如果不是,则不抛出任何错误.问题是我似乎无法在使用时设置参数:
I've been trying to do a text of a function that handles errors in a way that, if it is a valid error, it is thrown, but if it is not, then nothing is thrown. The problem is that i cant seem to set the parameter while using:
expect(handleError).to.throw(Error);
理想的方法是使用:
expect(handleError(validError)).to.throw(Error);
有什么方法可以实现此功能?
Is there any way to achieve this functionality?
函数代码:
function handleError (err) {
if (err !== true) {
switch (err) {
case xxx:
...
}
throw "stop js execution";
else {}
}
以及测试代码(未按预期工作):
And the code of the test (not working as intended):
it("should stop Javascript execution if the parameter isnt \"true\"", function() {
expect(handleError).to.be.a("function");
expect(handleError(true)).to.not.throw(Error);
expect(handleError("anything else")).to.throw(Error);
});
推荐答案
问题是您正在调用handleError,然后将结果传递给期望值.如果handleError抛出,则期望永远不会被调用.
The problem is that you are calling handleError, then passing the result to expect. If handleError throws, then expect never even gets called.
您需要将handleError的调用推迟到调用expected之前,以便Expect可以看到调用该函数时发生的情况.幸运的是,这是期望的:
You need to defer calling handleError until expect is called, so that expect can see what happens when the function is called. Fortunately, this is what expect wants:
expect(function () { handleError(true); }).to.not.throw();
expect(function () { handleError("anything else") }).to.throw("stop js execution");
如果您阅读了文档以进行抛出,则您会看到应该为相关的期望传递一个函数.
If you read the documentation for throw, you'll see that the associated expect should be passed a function.
这篇关于柴:是否期望错误取决于参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!