更改角度模拟值

时间:2015-04-02 07:57:31

标签: angularjs unit-testing karma-jasmine

我有一个单元测试,如下所示:

describe("myDirective Test",function(){
    beforeEach(module('app'));

    beforeEach(function() {
        module(function($provide) {
          $provide.constant('Config', {"showmenu":true});
        });
    });

    it('should add showmenu attribute',inject(function($compile,$rootScope){
        var element = $compile('<div my-directive></div>')($rootScope);
        expect(element.attr('showmenu')).not.toBe(undefined);
    }));

    it('should NOT add showmenu attribute',inject(function($compile,$rootScope){
        var element = $compile('<div my-directive></div>')($rootScope);
        expect(element.attr('showmenu')).toBe(undefined);
    }));
});

这是我的指示:

.directive('myDirective', ['$compile','Config', function($compile,Config){
    return {
        scope: true, 
        link: function(scope, element) {
            if(Config.showmenu){
                element.attr('showmenu', "{'height':menuheight,'alwaysVisible':true}"); 
                element.removeAttr('my-directive'); 
                $compile(element)(scope);
            }
        }
    };
}]);

如何更改showmenu值,使其在false测试中为should NOT add showmenu attribute

1 个答案:

答案 0 :(得分:1)

尝试将Config注入您的测试,并在那里进行更改:

it('should NOT add showmenu attribute',inject(function($compile,$rootScope, Config){
    Config.showmenu = false;
    var element = $compile('<div my-directive></div>')($rootScope);
    expect(element.attr('showmenu')).toBe(undefined);
}));

不确定您的真实代码是否类似,但此处有一个额外的空间:

 .directive('myDirective '