Unit Test Angular Form Validation Using $ validators

My webapp uses Angular 1.4.8 . I have a directive that validates form input using $ validators . Only input that starts with the numbers 5, 6 and 9 and contains 8 numbers is 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 to be valid
                    return true;
                }
                return REGEXP.test(viewValue);
            };
        }
    };
}

Using:

<form name="form">
    <input type="text" name="myInput" custom-number>
</form>

Now I want to write unit test for this directive using Jasmine . This is my 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 this operation causes an error "TypeError: Cannot set property 'customNumber' of undefinedon this line:

ctrl.$validators.customNumber = function(....

, $validators undefined , . , $validators , , customNumber ( ), form.$valid .

?

+4
1

ctrl - whare ctrl [0] - ngModel ctrl [1] - formController

+2

Source: https://habr.com/ru/post/1626320/


All Articles