Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai test failure with arguments

I can't seem to completely understand how to properly work with testing, specifically with Chai library. Or I might miss something from programming fundamentals, kinda confused.

Given test:

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

And this is a function I'm testing:

function testFunction(arg) {
    if (typeof arg === "number" || typeof arg === "string")
        throw new TypeError;
}

I was expecting for test to pass, but I'm just seeing that thrown error in the console:

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

Could someone please explain this to me?

like image 771
genesst Avatar asked Nov 16 '25 10:11

genesst


1 Answers

Your testFunction is called and - if no error is thrown - the result is passed to expect. So, as an error is being thrown, expect is not called.

You need to pass a function to expect that will call testFunction:

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

The expect implementation will see that it has been passed a function and will call it. It will then evaluate the expectations/assertions.

like image 69
cartant Avatar answered Nov 18 '25 04:11

cartant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!