angularjs – 在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);
                }
            });
        }
    };
}
]);

和茉莉花测试如下:

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

});

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

解决方法

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

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

scope: {
  isDirty: '=',isSaving: '='
}

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

将is-saving属性添加到元素:

elem = '<save-button is-saving="isSaving"></save-button>';

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

var el = createDirective();

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

expect(el.hasClass('btn-primary')).toBeFalsy();

演示: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();

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

scope: {
  isDirty: '='
}

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

Expression ‘undefined’ used with directive ‘saveButton’ is
non-assignable!
(07001$compile/nonassign?p0=undefined&p1=saveButton)

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

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...