继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进行无头测试,但谷歌浏览器自己测试它?
您是否尝试切换测试运行Chrome浏览器,看看该行为复制的浏览器? – AlvinJ 2014-11-24 21:32:50
还没有尝试过,因为它不是一个选项。该项目足够大,我们不能仅仅改变我们的测试套件。 – 2014-11-25 23:07:22
可能的重复http://stackoverflow.com/questions/24246811/testing-ng-if-using-compile – Adamy 2015-06-29 00:55:38