我在尝试使用javascript中的参数测试函数时遇到了一些严重的困难。我如何测试参数?
这是我的功能:
NotificationHelper.prototype.addNotificationItems = function(validationErrors) {
this.get$NotificationItems().html(render('tmpl-NotificationView-notificationItems', {items: validationErrors}))
};
validationErrors应该是一个对象,并且函数渲染在html代码中呈现手柄模板。它在循环中呈现一堆li,具体取决于对象中有多少属性。
我的问题是我需要测试这个论点?我需要测试所有类型吗?
//Filled object
notificationHelper.addNotificationItems({Street: 'Veuillez respecter le format requis.'});
expect($notificationItems.find('li').length).toEqual(1);
//Empty object
notificationHelper.addNotificationItems({});
expect($notificationItems.find('li').length).toEqual(0);
//Filled array
notificationHelper.addNotificationItems(['Street', 'Veuillez respecter le format requis.']);
expect($notificationItems.find('li').length).toEqual(0);
//Empty array
notificationHelper.addNotificationItems([]);
expect($notificationItems.find('li').length).toEqual(0);
//Undefined
notificationHelper.addNotificationItems(undefined);
expect($notificationItems.find('li').length).toEqual(0);
//Null
notificationHelper.addNotificationItems(null);
expect($notificationItems.find('li').length).toEqual(0);
//Boolean
notificationHelper.addNotificationItems(true);
expect($notificationItems.find('li').length).toEqual(0);
//Integer
notificationHelper.addNotificationItems(0);
expect($notificationItems.find('li').length).toEqual(0);
//String
notificationHelper.addNotificationItems('String');
expect($notificationItems.find('li').length).toEqual(0);
或者我只使我的函数接受一个对象参数:
NotificationHelper.prototype.addNotificationItems = function(validationErrors) {
if(typeof validationErrors == Object)
this.get$NotificationItems().html(render('tmpl-NotificationView-notificationItems', {items: validationErrors}))
};
如你所见,我迷失了...... 这也是这样做的好方法吗?我是否应该在函数中抛出一个错误,如果它不是好的类型,而不仅仅是检查它没有良好的行为?
答案 0 :(得分:1)
我会说,测试该函数的行为是否符合规定。不多也不少。
如果您指定,如果您有古怪的输入,某些事情会发生,那么您需要使用古怪的输入进行测试,以验证您所说的是真的。但是,尝试每一种情况都是不可能的。 (即使你只接受对象......你试过{ stuff: { probably: 'wrong' }}
吗?new String('heh')
怎么办?)所以你必须对你要测试的内容挑剔,否则你将会永远保持这种状态。
我建议 * :
return 42;
- 类型的存根); undefined
和数组)和'oops'
和前面提到的对象。)如果一个函数通过这些输入,那么你可以合理地确信其他怪异会触发正确的响应。
*好的。我撒了谎。我不会真的推荐任何这些东西。但如果你已经说过你的功能会做什么,那么你必须确保它能做到这一点。
我个人只会测试函数在呈现正确输入时的行为是否正常。然而,再次,我习惯于没有指定如果调用者不能遵循简单的指令会发生什么。 (当我们试图告诉我foo.thisClearlyWantsObjects('Im just learned js in 24 hours I like cheese')
不起作用时,这让我有权用2x4的线索敲打他们。至少,这就是我在审判中所说的话。我有信心没有陪审团我的同行会让我有罪。)