如何在角度指令测试中通过Id查找元素

时间:2015-02-02 22:49:59

标签: javascript angularjs jqlite

我有一个指令,在单元测试中呈现以下html:

<div id="published-envs">
    <strong>Published to</strong>
    <!-- ngRepeat: env in fundConfigurationVersion.publicationEnvironments --><div data-ng-repeat="env in fundConfigurationVersion.publicationEnvironments" class="ng-binding ng-scope">
            QA (Jan 29, 2015)
    </div><!-- end ngRepeat: env in publicationEnvironments --><div data-ng-repeat="env in publicationEnvironments" class="ng-binding ng-scope">
            PROD (Jan 30, 2015)
    </div><!-- end ngRepeat: env in publicationEnvironments -->
</div>

我试图抓住<div id="published-envs">并断言其中有两个孩子<div>

我尝试了以下但是它不起作用: var environments = element.find('#published-envs'); //comes back empty

在角度单位测试中通过id查找元素的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

根据Angular Element Docs.find()

  

仅限于按标记名称

进行查找

尝试

var environments = angular.element(document.getElementById('published-envs')).find('div');

JSFiddle Example

修改

对于已编译的标记,它基本上是相同的,只需注入$compile服务并使用如下

var comipledEnvironments = $compile(angular.element('<div id="published-envs"><div></div><div></div></div>'))($scope).find('div')

console.log(comipledEnvironments); // 2 <div>'s

Updated JSFiddle