Chai用参数测试失败

gen*_*sst 3 javascript mocha.js chai

我似乎无法完全理解如何正确地使用测试,特别是与Chai库.或者我可能会错过编程基础知识,有点困惑.

鉴于测试:

it("should check parameter type", function(){
    expect(testFunction(1)).to.throw(TypeError);
    expect(testFunction("test string")).to.throw(TypeError);
});
Run Code Online (Sandbox Code Playgroud)

这是我正在测试的一个功能:

function testFunction(arg) {
    if (typeof arg === "number" || typeof arg === "string")
        throw new TypeError;
}
Run Code Online (Sandbox Code Playgroud)

我期待测试通过,但我只是在控制台中看到抛出的错误:

TypeError: Test
    at Object.testFunction (index.js:10:19)
    at Context.<anonymous> (test\index.spec.js:31:28)
Run Code Online (Sandbox Code Playgroud)

有人可以向我解释一下吗?

car*_*ant 6

testFunction调用你的- 如果没有抛出错误 - 结果传递给expect.因此,当抛出错误时,expect不会被调用.

你需要传递一个函数来expect调用testFunction:

it("should check parameter type", function(){
    expect(function () { testFunction(1); }).to.throw(TypeError);
    expect(function () { testFunction("test string"); }).to.throw(TypeError);
});
Run Code Online (Sandbox Code Playgroud)

expect实施会看到,它已经通过了一项功能,并调用它.然后它将评估期望/断言.