测试添加$ parser的angular指令

时间:2016-10-20 11:16:42

标签: angularjs-directive jasmine

我有一个指令,用于验证文本是否采用特定格式:

angular.module('app')
    .directive('validNumber', validNumber);

function validNumber() {
    var directive = {
        restrict: 'A',
        require: '?ngModel',
        link: linkFunc
    };

    return directive;

    function linkFunc(scope, element, attrs, ngModelCtrl) {
        if (!ngModelCtrl) {
            return;
        }

        ngModelCtrl.$parsers.push(function (val) {
            if (angular.isUndefined(val)) {
                var val = '';
            }

            var clean = val.replace(/[^0-9\.]/g, '');
            var decimalCheck = clean.split('.');

            if (!angular.isUndefined(decimalCheck[1])) {
                decimalCheck[1] = decimalCheck[1].slice(0, 2);
                clean = decimalCheck[0] + '.' + decimalCheck[1];
            }

            if (val !== clean) {
                ngModelCtrl.$setViewValue(clean);
                ngModelCtrl.$render();
            }
            return clean;
        });

        element.bind('keypress', function (event) {
            if (event.keyCode === 32) {
                event.preventDefault();
            }
        });
    }
}

现在我想测试我添加的内部解析器函数,我就是不能这样做。如何调用该函数的调用?我该如何测试结果?我非常不成功的测试是:

describe('validNumber directive specs', function () {
    var scope, compile;

    var validHtml = '<form name="testForm"><input name="test" type="text" valid-number ng-model="str" /></form>';

    beforeEach(function () {
        angular.mock.module('dashboardApp');
        module(bootstrapperMock);
        inject(function (_$rootScope_, _$compile_) {
            scope = _$rootScope_.$new();
            compile = _$compile_;
        });
    });

    describe('When a key press occures', function () {
       it('should :( ', function () {
           scope.str = 0;
           var element = compile(validHtml)(scope);
           var viewValue = 2, input = element.find('input');
           scope.str = viewValue;
           scope.$digest();
           var e = angular.element.Event('keypress keydown');
           e.which = 50;
           element.trigger(e);
           scope.$digest();
       });
    });
});

我尝试更改模型并触发按键。 谢谢!

1 个答案:

答案 0 :(得分:0)

以下作品:

describe('When a key press occures', function () {
       it('when a key press', function () {
           var expected = '';

           var element = compile(validHtml)(scope);
           element.val('asda');
           element.trigger('input');

           var actual = element.val();

           expect(expected).toBe(actual);
       });
    });

我还更新了此规范中的html:

var validHtml = '<input name="test" type="text" valid-number ng-model="str" />';

这里的神奇之处在于触发&#39;输入&#39;对于元素。