如何在使用Mocha/Chai的函数中使用某些参数时正确抛出TypeError

How to correctly throw an TypeError when certain parameters are used in a function using Mocha/Chai

本文关键字:参数 TypeError 函数 Mocha Chai      更新时间:2023-09-26

所以,我得到了这个代码:

function initial(a,b,c){
    if ( isNaN(a) || isNaN(b) || isNaN(c) ){
        //do something
    }
    else {
        //do something
    }  
}

当使用字符串而不是数字时,我需要期望TypeError。最初我认为分别声明a, bc的期望是可以的,像这样:

 expect(a).to.be.a('number');
 expect(b).to.be.a('number');
 expect(c).to.be.a('number');

我希望它实际观察函数并期望某些参数抛出错误,例如:

expect( initial('foo','foo','foo') ).to.Throw(TypeError);

但这是不工作,我已经测试了相当多的选项,似乎没有实际给我的TypeError我想要的。有人知道期望某些函数参数的正确方法吗?

那么,函数:

function initial(a, b, c) {
    if ([...arguments].filter(isNaN).length > 0) {
        throw 'Function received a non-number';
    } else {
        return 'ok!';
    }
}

你可以这样测试它的行为:

describe('test my function', function() {
    it('should throw when wrong arguments passed', function() {
        let res, err;
        try {
            res = initial(1, 'a', 3);
        } catch (e) {
            err = e;
        }
        expect(!!res).to.equal(false);
        expect(err).to.equal('Function received a non-number');
    });
    it('should return the expected result', function() {
        let res = initial(1, 2, 3);
        expect(res).to.equal('ok!');
    });
});

jsFiddle: https://jsfiddle.net/ywz6djqb/