柴:根据参数预期错误与否

Apz*_*pzx 21 javascript mocha.js chai

我一直在尝试做一个函数的文本来处理错误,如果它是一个有效的错误,它会被抛出,但如果不是,那么什么都不会抛出.问题是我似乎无法在使用时设置参数:

expect(handleError).to.throw(Error);
Run Code Online (Sandbox Code Playgroud)

理想的是使用:

expect(handleError(validError)).to.throw(Error);
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这个功能?

功能代码:

function handleError (err) {
    if (err !== true) {
        switch (err) {
            case xxx:
            ...
        }
        throw "stop js execution";
    else {}
}
Run Code Online (Sandbox Code Playgroud)

和测试代码(不按预期工作):

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);
});
Run Code Online (Sandbox Code Playgroud)

Dav*_*man 41

问题是您正在调用handleError,然后将结果传递给expect.如果handleError抛出,那么期望永远不会被调用.

你需要推迟调用handleError直到调用expect,这样expect才能看到调用函数时会发生什么.幸运的是,这是期望的:

expect(function () { handleError(true); }).to.not.throw();
expect(function () { handleError("anything else") }).to.throw("stop js execution");
Run Code Online (Sandbox Code Playgroud)

如果您阅读了throw 的文档,您将看到相关的期望应该传递给函数.

  • 我去了`expect(() => throwAnError(true)).to.throw()`; (2认同)

Sve*_*ung 7

我今天遇到了同样的问题,并选择了另一个未提及的解决方案:部分功能应用程序使用bind():

expect(handleError.bind(null, true)).to.not.throw();
expect(handleError.bind(null, "anything else")).to.throw("stop js execution");
Run Code Online (Sandbox Code Playgroud)

这样做的好处是简洁,使用普通的JavaScript,不需要额外的功能,你甚至可以提供this你的功能依赖它的价值.