单元测试调用ngModelCtrl。$ render in Directive

时间:2016-02-25 14:03:05

标签: angularjs unit-testing angularjs-directive angularjs-ng-model

尝试对ngModelCtrl上的调用进行单元测试。$ render。现在通过$ setViewValue但实际上我想在指令上设置ng-model的值并测试是否调用了$ render。

指令:

angular.module('inputValidationBelow', []).directive('inputValidationBelow', function ($compile) {
    return {
        scope: {
            dataModel: '=ngModel',
            placeHolder: '@',
            identifier: '@',
            feedbackMessage: '@',
            type: '@'
        },
        templateUrl: 'scripts/directives/inputValidationBelow/inputValidationBelow.html',
        restrict: 'E',
        transclude: true,
        replace: false,
        require: ['ngModel', '^form'],
        link: function (scope, element, attrs, controllers) {

            scope.type = attrs.type;

            var ngModelController = controllers[0];

            ngModelController.$render = function () {
                if (typeof ngModelController.$viewValue !== 'undefined') {
                    scope.dataModel = ngModelController.$viewValue;
                }
            };
        }
    };
});

单元测试

it('should invoke ngModelCtrl.$render after changing value on ngModel from the outside (the view)', function () {
    var scope,
        element,
        ngModelCtrl,
        modelValue;

    scope = $rootScope.$new();
    element = angular.element('<form name="loginForm"><input-validation-below place-holder="foo"  feedback-message="bar" identifier="username" ng-model="login"></input-validation-below></form>');

    element = $compile(element)(scope);
    scope.$digest();

    var ngModelCtrl = element.find('input-validation-below').controller('ngModel');

    modelValue = {username: 'SJV'};
    ngModelCtrl.$setViewValue(modelValue);

    scope.$digest();

    expect(scope.dataModel).toEqual(modelValue);
});

测试失败:Expected undefined to equal { username : 'SJV' }

我在Angular文档中读到了这个:

Since ng-model does not do a deep watch, $render() is only invoked if the values of $modelValue and $viewValue are actually different from their previous value. If $modelValue or $viewValue are objects (rather than a string or number) then $render() will not be invoked if you only change a property on the objects.

但这让我感到困惑。

但是,我需要调用$ render来从外部更改ng-model以使其尽可能真实,并且代码覆盖范围覆盖其代码。

问题:可以使用一些指针。

0 个答案:

没有答案