更改 Angular 模拟值

Change Angular mock value

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

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 值,使其在 should NOT add showmenu attribute 测试中为 false

尝试将 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);
}));

不确定你的真实代码是否是那样的,但你这里有一个额外的space:

 .directive('myDirective '