【问题标题】:How to correctly throw an TypeError when certain parameters are used in a function using Mocha/Chai在使用 Mocha/Chai 的函数中使用某些参数时如何正确抛出 TypeError
【发布时间】:2017-01-19 06:04:38
【问题描述】:

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

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

但这不起作用,我已经测试了很多选项,但似乎没有一个真正给我我想要的 TypeError。有没有人知道期望某些函数参数的正确方法?

【问题讨论】:

  • 使用throw new TypeError('message');
  • @japrescott 我实际上并不是在谈论 TypeError 部分,而是如何期望某些函数参数。也许我没有正确表达自己。你知道怎么做吗?

标签: javascript node.js unit-testing mocha.js chai


【解决方案1】:

所以,有这样的功能:

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/

【讨论】:

  • 酷,它有效!但是没有办法只用一行来写吗?
  • @PauloGabriel 取决于你想测试什么,你能更好地描述你的需求吗?
  • 我需要测试我的函数中可能出现的错误,例如将“字符串”作为参数之一,或者使用 0。我想实际列出错误参数的示例并抛出错误,例如: expect( initial(1,1,'foo') ).to.Throw(TypeError); expect( initial('foo','foo','foo') ).to.Throw(TypeError); 在某些时候我使用过 expect( function(){initial('foo','foo','foo')} ).to.Throw(TypeError); 但它一直说函数 initial 没有定义。
  • @PauloGabriel 传递错误数据时函数内部会发生什么?函数throw 应该吗?在这种情况下,您需要在其外部使用 try/catch 来对其进行测试。
  • 我没有。我什至认为我没有正确设置文件,我的测试文件实际上并没有读取我的主脚本。我得再复习一下!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 2015-06-02
  • 1970-01-01
  • 2020-08-29
相关资源
最近更新 更多