在为 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。
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/