指令范围变量在jasmine测试中无法访问

Pri*_*nda 3 angularjs angularjs-directive angularjs-scope karma-jasmine

我有一个如下指令:

angular.module('buttonModule', []).directive('saveButton', [
function () {

    function resetButton(element) {
        element.removeClass('btn-primary');
    }
    return {
        restrict: 'E',
        replace: 'false',
        scope: {
            isSave: '='
        },
        template:
            '<button class="btn" href="#" style="margin-right:10px;" ng-disabled="!isSave">' +

            '</button>',
        link: function (scope, element) {               
            console.log(scope.isSave);
            scope.$watch('isSave', function () {
                if (scope.isSave) {
                    resetButton(scope, element);
                }
            });
        }
    };
}
]);
Run Code Online (Sandbox Code Playgroud)

和茉莉花测试如下:

describe('Directives: saveButton', function() {

var scope, compile;

beforeEach(module('buttonModule'));

beforeEach(inject(function($compile, $rootScope) {
    scope = $rootScope.$new();
    compile = $compile;
}));

function createDirective() {
    var elem, compiledElem;
    elem = angular.element('<save-button></save-button>');
    compiledElem = compile(elem)(scope);
    scope.$digest();

    return compiledElem;    
}

it('should set button clean', function() {

    var el = createDirective();
    el.scope().isSaving = true;
    expect(el.hasClass('btn-primary')).toBeFalsy();     
});

});
Run Code Online (Sandbox Code Playgroud)

问题是isSaving的值没有反映在指令中,因此从不调用resetButton函数.如何访问规范中的指令范围并更改变量值.我尝试使用isolateScope,但同样的问题仍然存在.

tas*_*ATT 7

首先请注意,resetButton当您只接受一个参数时,您将使用两个参数调用该函数.我在我的示例代码中解决了这个问题 我还将类添加btn-primary到按钮元素中以使测试更清晰.

您的指令是在外部作用域和隔离作用域之间设置双向数据绑定:

scope: {
  isDirty: '=',
  isSaving: '='
}
Run Code Online (Sandbox Code Playgroud)

您应该利用它来修改isSaving变量.

is-saving属性添加到元素:

elem = '<save-button is-saving="isSaving"></save-button>';
Run Code Online (Sandbox Code Playgroud)

然后修改isSaving编译时使用的作用域的属性(您还需要触发摘要循环以使观察者检测到更改):

var el = createDirective();

scope.isSaving = true;
scope.$apply();

expect(el.hasClass('btn-primary')).toBeFalsy();
Run Code Online (Sandbox Code Playgroud)

演示: http ://plnkr.co/edit/Fr08guUMIxTLYTY0wTW3?p = preview

如果您不想将is-saving属性添加到元素中并仍想修改变量,则需要检索隔离范围:

var el = createDirective();

var isolatedScope = el.isolateScope();
isolatedScope.isSaving = true;
isolatedScope.$apply();

expect(el.hasClass('btn-primary')).toBeFalsy();
Run Code Online (Sandbox Code Playgroud)

为此,您需要删除双向绑定isSaving:

scope: {
  isDirty: '='
}
Run Code Online (Sandbox Code Playgroud)

否则它会尝试绑定到不存在的东西is-saving,因为元素上没有属性,您将收到以下错误:

与'saveButton'指令一起使用的表达式'undefined'是不可赋值的!(https://docs.angularjs.org/error/ $ compile/nonassign?p0 = undefined&p1 = saveButton)

演示: http ://plnkr.co/edit/Ud6nK2qYxzQMi6fXNw1t?p = preview