This custom validation directive is an example presented at the official angular site.
http://docs.angularjs.org/guide/forms
It checks a text input is in number format or not.
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;
}
});
}
};
});
To unit test this code, I wrote this:
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);
});
});
});
});
Then I get this error:
Expected undefined to equal 5.
Error: Expected undefined to equal 5.
I put print statements everywhere to see what is going on, and it looks like the directive is never called.
What is a proper way to test a simple directive like this?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…