Javascript 带参数的测试失败

Javascript 带参数的测试失败,javascript,mocha.js,chai,Javascript,Mocha.js,Chai,我似乎不能完全理解如何正确地使用测试,特别是使用Chai库。或者我可能会错过一些编程基础知识,有点困惑 给定测试: it("should check parameter type", function(){ expect(testFunction(1)).to.throw(TypeError); expect(testFunction("test string")).to.throw(TypeError); }); 这是我正在测试的一个函数: function testFunc

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

给定测试:

it("should check parameter type", function(){
    expect(testFunction(1)).to.throw(TypeError);
    expect(testFunction("test string")).to.throw(TypeError);
});
这是我正在测试的一个函数:

function testFunction(arg) {
    if (typeof arg === "number" || typeof arg === "string")
        throw new TypeError;
}
我期望测试通过,但我只是看到控制台中抛出的错误:

TypeError: Test
    at Object.testFunction (index.js:10:19)
    at Context.<anonymous> (test\index.spec.js:31:28)
TypeError:测试
在Object.testFunction(index.js:10:19)
在上下文中。(test\index.spec.js:31:28)

有人能给我解释一下吗?

您的
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);
});

expect
实现将看到它已经被传递了一个函数,并将调用它。然后,它将评估期望/断言。

谢谢,这已经奏效了。在这种类型的类型检查中抛出TypeError是正常的吗?我的意思是,如果我在prod env中使用这种逻辑(比如基于node.js),这会导致整个应用程序终止吗?如果收到意外参数,抛出类型错误是合适的;例如,节点的API就是这样做的。如果错误没有得到处理,是的,进程将终止。