编程语言
首页 > 编程语言> > javascript – Chai测试失败的参数

javascript – Chai测试失败的参数

作者:互联网

我似乎无法完全理解如何正确地使用测试,特别是与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.

你需要传递一个函数来期望它将调用testFunction:

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

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

标签:chai,javascript,mocha
来源: https://codeday.me/bug/20190828/1753530.html