繼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