加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 如何在AngularJS单元测试中向DOM添加div?

发布时间:2020-12-17 07:12:32 所属栏目:安全 来源:网络整理
导读:我在一个指令中使用以下代码来放置一个工具提示 var bodyoffset = document.querySelector(".smallcontainer-content").getBoundingClientRect();var width = elm.width();if(bodyoffset != undefined){ var tooltipDiv = document.querySelector(".tooltip"
我在一个指令中使用以下代码来放置一个工具提示

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,以便我可以测试我的所有功能?

解决方法

这是我如何设法做到的:

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的中途测试代码示例中发现了这一点

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读