2014-11-24 90 views
1

this question我用下面的方法来尝试测试是否NG-如果标签的div是正确显示使用噶,而不是量角器:测试NG-IF的div与单元正确显示测试

var element; 

beforeEach(inject(function ($rootScope, $templateCache, $compile) { 
    scope = $rootScope.new(); 
    fooController.init(scope); //Some controller function that sets properties on the scope 
          //which are tested for in the template 
    scope.$digest(); 
    var template = $templateCache.get('/my/template'); //Get the cached template 
    var compiled = compile(template)(scope);   //Compile it 

    element = angular.element(compiled);    //Wrap it with jQuery functions 
})); 

it('should do something', function() { 
    var div = element.find('#someDiv'); //Get some div that should be affected by ng-if 
    expect(div.html()).toBeUndefined(); //Expect the div not to be shown due to properties that 
             //were set by fooController.init 
}); 

我的模板有这样的事情:

<!-- scope.shown should be set to false by fooController.init --> 
<div id = "someDiv" ng-if = "shown">Foo</div> 

在这里,我使用expect(div.html()).toBeUndefined();因为ngIf(不像ngShow和ngHide)将删除DOM整个DIV如果条件中的计算结果为假(ngShow和ngHide应用类分区o导致它不被显示)。

但是,当我运行这个并打印出编译变量时,我发现ngIf div的HTML总是被带走并被替换为注释,而不管scope.shown的值如何。

Karma使用的Angular编译函数的工作方式与Angular本身在浏览器中的实际渲染方式不一样吗?我问,因为当我用浏览器测试它时,它显示正确,但是当我尝试单元测试时,它会输出错误的信息。也许这也是因为我正在使用PhantomJS进行无头测试,但谷歌浏览器自己测试它?

+0

您是否尝试切换测试运行Chrome浏览器,看看该行为复制的浏览器? – AlvinJ 2014-11-24 21:32:50

+0

还没有尝试过,因为它不是一个选项。该项目足够大,我们不能仅仅改变我们的测试套件。 – 2014-11-25 23:07:22

+0

可能的重复http://stackoverflow.com/questions/24246811/testing-ng-if-using-compile – Adamy 2015-06-29 00:55:38

回答

0

您需要评估显示在您的模板中。尝试创建一个返回true或false的函数。然后将其添加到您的模板。

ng-if = "GetShown([parameters]) === true" 

所以在您的控制器功能将像

$scope.GetShown = function([parameters]){ 
    return [evaluation] 
}; 
+0

不幸的是,这不起作用,但谢谢你的建议。 – 2014-11-25 23:06:52

+0

没问题,我很抱歉,我不能有更多的帮助。我想我应该发表评论而不是回答。我更新堆栈溢出,所以我表示歉意。 – Michael 2014-12-01 19:20:58