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

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

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

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

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

 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);

但这不起作用,我已经测试了很多选项,none 似乎实际上给了我我想要的 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/