如何在使用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。最初我认为分别声明a
, b
和c
的期望是可以的,像这样:
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/
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 要求未定义JS回调参数
- 我的jQuery插件参数没有正确启动,遇到了问题
- TypeError:无法读取属性'推'未定义的JavaScript
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- 当我将参数设置为对象时,JavaScript返回TypeError
- 抛出消息;TypeError:第一个参数必须是字符串或Buffer
- html5拖动&drop-TypeError:Node.appendChild的参数1不是对象
- Grunt:抛出新的TypeError(路径.resolve的参数必须是字符串');
- TypeError:Window.postMessage的参数不足
- Can't .join()函数参数- TypeError: undefined不是函数
- 如何在使用Mocha/Chai的函数中使用某些参数时正确抛出TypeError
- node.js和PostgreSQL query - throw new TypeError('第一个参数必须是
- TypeError:使用Node.js fs.read()的参数不正确
- TypeError:Node.appendChild的参数1未实现接口Node
- jQuery使用typeahead updatater参数抛出typeError