加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:08:06 所属栏目:安全 来源:网络整理
导读:我有一个如下指令: angular.module('buttonModule',[]).directive('saveButton',[function () { function resetButton(element) { element.removeClass('btn-primary'); } return { restrict: 'E',replace: 'false',scope: { isSave: '=' },template: 'butt
我有一个如下指令:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读