lundi 29 août 2016

Unit test $parsers in Angular directive

I'm trying to test custom directive that checks period of time validity:

angular.module('my-module')
    .directive('periodValidity', periodValidityDirective);

function periodValidityDirective () {
    var PERIOD_REGEXP = /^P([0-9]+Y|)?([0-9]+M|)?([0-9]+W|)?([0-9]+D)?(T([0-9]+H)?([0-9]+M)([0-9]+S)|T([0-9]+H)?([0-9]+M)?([0-9]+S)|T([0-9]+H)?([0-9]+M)([0-9]+S)?|T([0-9]+H)([0-9]+M)([0-9]+S)|T([0-9]+H)([0-9]+M)?([0-9]+S)?|T([0-9]+H)([0-9]+M)([0-9]+S)?)?$/;
        return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                if (viewValue === '' || PERIOD_REGEXP.test(viewValue)) {
                    ctrl.$setValidity('period', true);
                    return viewValue;
                } else {
                    ctrl.$setValidity('period', false);
                    return undefined;
                }
            });
        }
    };
}

Second test can not pass. scope.model.period is not undefinded and form.period is valid.

var element,
    scope,
    form;

beforeEach(module('my-module'));
beforeEach(inject(function($compile, $rootScope){
    scope = $rootScope;
    element = angular.element(
        '<form name="form">' +
         '<input  type="text" ng-model="model.period" name="period" period-validity />' +
        '</form>'
    );
    scope.model = { period: null };
    $compile(element)(scope);
    scope.$digest();
    form = scope.form;
}));

describe('string', function() {
    it('should pass with good period', function() {
        form.period.$setViewValue('PT2H3M5S');
        scope.$digest();
        expect(scope.model.period).toEqual('PT2H3M5S');
        expect(form.period.$valid).toBe(true);

    });
    it('should not pass with bad period', function() {
        form.period.$setViewValue('1H');
        scope.$digest();
        expect(scope.model.period).toBeUndefined();
        expect(form.period.$valid).toBe(false);
    });
});

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire