如何使用jasmine对我的自定义指令进行单元测试?

时间:2014-09-07 04:15:22

标签: unit-testing angularjs-directive karma-jasmine

我正在尝试对我的自定义角度js指令进行单元测试。该指令基于正则表达式进行日期验证:

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;
            });
        }
    };
});

我的规格如下:

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);
    });
});

我正在努力解决的问题是如何在单元测试中“运行”指令?

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

1 个答案:

答案 0 :(得分:2)

你可以做这样的事情..

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