2013-08-01 63 views
10

我使用的指令下面的代碼放置工具提示如何在AngularJS單元測試中將DOM添加到DOM中?

var bodyoffset = document.querySelector(".smallcontainer-content").getBoundingClientRect(); 
var width = elm.width(); 
if(bodyoffset != undefined){ 
    var tooltipDiv = document.querySelector(".tooltip"); 
    angular.element(tooltipDiv).css("top", offset.top-bodyoffset.top+"px"); 
    angular.element(tooltipDiv).css("left", offset.left-bodyoffset.left+width+5+"px"); 
} 

這並不在單元測試的DIV類「smallcontainer」是不存在的工作。我怎樣才能確保在單元測試中創建div,以便我可以測試我所有的功能?

回答

14

這是我成功地做到這一點。

beforeEach(inject(
    ['$compile','$rootScope', function(_$compile_) { 
     var html = '<div class="smallcontainer-content"></div>'; 
     angular.element(document.body).append(html); 
     elm = angular.element('<form name="form"><input name="password" id="passwordInput" data-ng-model="password" size="25" type="password" maxlength="20" tabindex="1" autofocus data-my-password-check></form>'); 
     $compile(elm)($rootScope); 
     form = $rootScope.form; 

    }] 
)); 

重要這兒的一部分它增加了對HTML文檔是angular.element()追加()。

我在中途測試代碼示例http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html#testing-filters

相關問題