javascript - 为什么 Angular.element/jqlite 找不到顶级元素?

标签 javascript angularjs karma-runner chai

在为 Angular View 编写 Mocha/Chai 测试时,我发现 jqlite(因为我没有使用 jQuery)无法找到顶级元素。

我将其归结为一个简单的示例:

/* jshint expr:true */
describe( "View", function() {
    'use strict';

    var $compile, $rootScope;
    beforeEach( inject( function( _$compile_, _$rootScope_ ) {
            $compile = _$compile_;
            $rootScope = _$rootScope_;
    } ) );

    var view;
    beforeEach( function() {
        var html = "<div><span>div[0].span</span><p>div[0].p</p></div><div><h1>div[1].h1</h1><p>div[1].p</div>";
        view = $compile( angular.element( html ) )( $rootScope );
    } );

    it( "should find two p tags", function() {
        expect( view.find( "p" ).length ).to.equal( 2 );
    } );

    it( "should find one span tag", function() {
        expect( view.find( "span" ).length ).to.equal( 1 );
    } );

    it( "should find two div tags", function() {
        expect( view.find( "div" ).length ).to.equal( 2 );
    } );


} );

在此示例中,前两个测试通过,第三个测试失败:

View
    ✓ should find two p tags
    ✓ should find one span tag
    ✗ should find two div tags
    AssertionError: expected 0 to equal 2
        at ...

这似乎是因为 div 是顶级元素,span 和 p 标签位于它们下方。如果我将整个内容包含在另一个标签中,则第三个测试将开始通过。

为什么?

最佳答案

.find 仅搜索后代,因此答案将为 0。

来自http://api.jquery.com/find/

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree

关于javascript - 为什么 Angular.element/jqlite 找不到顶级元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26282167/

相关文章:

javascript - 单击按钮时打开空白窗口

javascript - TypeError : app. use() 需要中间件函数

javascript - 等待在 AngularJS/通用 javascript 中应用更改?

AngularJS 翻译 : How to handle form text with link?

unit-testing - 将模拟 DOM 事件传递给没有 jQuery 的指令处理程序

unit-testing - KarmaJS、Jasmine、RequireJS 等 : How to Use Require for Testing Modules

javascript - 为什么我应该在 Person Constructor(和类似的构造函数)中使用 `this.name` 而不是 `name`?

javascript - 通过 Javascript 连接到 Facebook API 时如何重新加载/刷新 facebook like 按钮

angularjs - 在 AngularJS 应用程序中预填充远程数据的最佳方法

node.js - 错误 [ karma ] : [TypeError: Cannot call method 'push' of undefined] when adding HTML output