This custom validation directive is an example provided on the official angular website. http://docs.angularjs.org/guide/forms It checks whether text input is in numeric 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; } }); } }; });
In unit test this code, I wrote the following:
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 print print statements everywhere to see what happens, and it looks like the directive is never called. What is the correct way to test a simple directive like this?
angularjs unit-testing angularjs-directive
ghiden Mar 05 '13 at 9:07 2013-03-05 09:07
source share