此自定义验证指令是在官方角度网站上提供的示例。 http://docs.angularjs.org/guide/forms 它检查文本输入是否是数字格式。测试自定义验证angularjs指令
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.
我把打印语句随处可见,看看是怎么回事,和它看起来像指令永远不会被调用。 什么是测试像这样的简单指令的正确方法?
感谢您花时间带回答案!只是FYI,你可以提取你的答案,并将其标记为后来搜索者接受的答案 - 在这里可以接受;-) – 2013-06-25 01:05:58
谢谢你的提示。我提出了我的答案。 – ghiden 2013-07-06 07:54:22