带有参数的 Chai 测试失败
Chai test failure with arguments
我似乎无法完全理解如何正确地进行测试,特别是 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)
有人可以给我解释一下吗?
你的 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
实现将看到它已传递一个函数并将调用它。然后它将评估 expectations/assertions.
我似乎无法完全理解如何正确地进行测试,特别是 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)
有人可以给我解释一下吗?
你的 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
实现将看到它已传递一个函数并将调用它。然后它将评估 expectations/assertions.