user603007
user603007

Reputation: 11804

how can I unit test my custom directive using jasmine?

I am trying to unit test my custom angular js directive. The directive does a date validation based on a regex:

var app = angular.module('myApp', []);

app.directive('myValidation', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attr, ctrl) {
            var regex = new RegExp(attr.myValidation);
            ctrl.$parsers.unshift(function (value) {
                var valid = regex.test(value);
                ctrl.$setValidity('myValidation', valid);
                console.log('valid?', valid);
                console.log('value?', value);
                return valid ? value : undefined;
            });
            ctrl.$formatters.unshift(function (value) {
                ctrl.$setValidity('regexValidate', regex.test(value));
                return value;
            });
        }
    };
});

My spec looks like this:

describe('Testing myValidation directive', function() {
    var scope,
        elem,
        directive,
        compiled,
        html,
        ctrl;

    beforeEach(function (){
        module('myApp');
        html = '<input type="text"  ng-model="test" name="test" ng-minlength="50" my-validation="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d$" />'
        inject(function($compile, $rootScope,$controller) {
            scope = $rootScope.$new();
            elem = angular.element(html);
            compiled = $compile(elem);
            compiled(scope);
            ctrl=elem.controller('myValidation');
            ctrl=$controller;
            scope.$digest();
        });
    });

    it('Should result in valid datetime validation', function() {
        var date='27/01/2000';

        ctrl.$viewValue=date;
        scope.$apply();

        expect(ctrl.Validity).toBe(true);
    });
});

The bit I am struggling with is how to 'run' the directive in the unit test?

plunkr ref:http://plnkr.co/edit/d4buHW8x7fMh8Hl5JKze?p=preview

Upvotes: 2

Views: 897

Answers (1)

Mullaguri Kedhar
Mullaguri Kedhar

Reputation: 21

You can just do something like this..

it('Description', function () {    
  elem .val("27/01/2000");    
  elem .trigger("input");    
  $scope.$digest();    
  expect(elem.hasClass('ng-invalid')).toBeTruthy();    
});

Upvotes: 2

Related Questions