如何测试这个指令?

时间:2014-05-14 13:28:20

标签: angularjs angularjs-directive jasmine karma-runner jasmine-jquery

如何测试此指令?

angular.module('uiApp')
.directive('uppercase', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            var uppercase = function (value) {
                var uppercase = value.toUpperCase();
                if (uppercase !== value) {
                    ngModelCtrl.$setViewValue(uppercase);
                    ngModelCtrl.$render();
                }
                return uppercase;
            };
            ngModelCtrl.$parsers.push(uppercase);
        }
    };
});

我尝试过这种方法,但它不起作用:

it('should transform to uppercase', inject(function ($compile) {
    element = angular.element('<input type="text" ng-model="test" ng-init="test=\'test\'" uppercase>');
    element = $compile(element)(scope);
    expect(element.text()).toBe('TEST');
}));

2 个答案:

答案 0 :(得分:3)

我知道了:

it('should transform to uppercase', inject(function ($compile) {
    scope.test = '';
    element = angular.element('<input type="text" ng-model="test" uppercase>');
    element = $compile(element)(scope);
    element.val('test').triggerHandler('input');
    expect(element.val()).toBe('TEST');
    expect(scope.test).toBe('TEST');
}));

它有效。显然trigger('input')是关键。

答案 1 :(得分:1)

您需要在链接功能中将uppercase附加到$formatters,而不是$parsers

ngModelCtrl.$formatters.push(uppercase);

然后像这样测试:

it('should transform to uppercase', inject(function ($compile, $rootScope, $timeout) {
    $rootScope.test = 'test';
    element = angular.element('<input type="text" ng-model="test" uppercase>');
    element = $compile(element)($rootScope);
    $rootScope.$apply();
    expect(element.val()).toBe('TEST');
}));