【发布时间】:2013-02-19 14:42:45
【问题描述】:
这个自定义验证指令是官方 Angular 网站上的一个示例。 http://docs.angularjs.org/guide/forms 它检查文本输入是否为数字格式。
var INTEGER_REGEXP = /^\-?\d*$/;
app.directive('integer', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('integer', true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('integer', false);
return undefined;
}
});
}
};
});
为了对这段代码进行单元测试,我写了这个:
describe('directives', function() {
beforeEach(module('exampleDirective'));
describe('integer', function() {
it('should validate an integer', function() {
inject(function($compile, $rootScope) {
var element = angular.element(
'<form name="form">' +
'<input ng-model="someNum" name="someNum" integer>' +
'</form>'
);
$compile(element)($rootScope);
$rootScope.$digest();
element.find('input').val(5);
expect($rootScope.someNum).toEqual(5);
});
});
});
});
然后我得到这个错误:
Expected undefined to equal 5.
Error: Expected undefined to equal 5.
我将打印语句放在各处以查看发生了什么,看起来该指令从未被调用过。 测试这样一个简单指令的正确方法是什么?
【问题讨论】:
-
感谢您抽出宝贵时间回复答案!仅供参考,您可以提取您的答案并将其标记为已接受的答案以供以后的搜索者使用——这在此处是可以接受的;-)
-
感谢您的提示。我移动了我的答案。
标签: unit-testing angularjs angularjs-directive