angularjs - Unit Test Angular Form Validation With $validators -
my webapp using angular 1.4.8. have directive validates form input using $validators. input starts number 5, 6 , 9 , contains 8 numbers valid.
angular .module('directive.customnumber', []) .directive('customnumber', customnumber); function customnumber() { var regexp = /^([569][0-9]{7})/; return { require: ['ngmodel', '^form'], link: function(scope, elm, attrs, ctrl) { ctrl.$validators.customnumber = function(modelvalue, viewvalue) { if(ctrl.$isempty(modelvalue)) { // consider empty models valid return true; } return regexp.test(viewvalue); }; } }; }
usage:
<form name="form"> <input type="text" name="myinput" custom-number> </form>
now want write unit test directive using jasmine. test case:
describe('directive', function() { var $scope; beforeeach(function() { module('directive.customnumber'); inject(function($rootscope, $compile) { $scope = $rootscope; var template = '<form name="form"><input type="text" name="myinput" custom-number></form>'; $compile(template)($scope); $scope.digest(); }); }); it('should not accept invalid input', function() { var form = $scope.form; form.myinput.$setviewvalue('abc'); expect(form.$valid).tobefalsy(); expect(form.myinput.$error.mobile).tobedefined(); }); });
running throws error "typeerror: cannot set property 'customnumber' of undefined
@ line:
ctrl.$validators.customnumber = function(....
i not sure why $validators
become undefined in test works fine in normal environment. if rid of error manually creating $validators
object before use, test fails because customnumber
validator never being run (know logging), form.$valid
true.
how can test directive?
on directive ctrl array whare ctrl[0] ngmodel , ctrl[1] formcontroller
Comments
Post a Comment