【问题标题】:How to add a div to the DOM in AngularJS unit tests?如何在 AngularJS 单元测试中向 DOM 添加 div?
【发布时间】:2013-08-02 05:49:43
【问题描述】:

我在指令中使用以下代码来放置工具提示

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");
}

这在单元测试中不起作用,因为类“smallcontainer”所在的 div 不存在。如何确保在单元测试中创建了 div,以便我可以测试我的所有功能?

【问题讨论】:

    标签: unit-testing angularjs directive


    【解决方案1】:

    这就是我设法做到的:

    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().append()。

    我在http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html#testing-filters的中途测试代码示例中发现了这个

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-18
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      相关资源
      最近更新 更多