在为角度视图编写Mocha/Chai测试时,我发现jqlite(因为我没有使用jQuery)不会找到顶级元素。为什么Angular.element/jqlite找不到顶级元素?
我煮下来到一个简单的例子:
/* 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 ...
这似乎是因为申报单是顶级元素,span和p标签在它们下面。如果我把所有东西都放在另一个标签中,第三个测试就会开始通过。
为什么?
注:使用jQuery,至少,你可以使用['.filter() '](http://api.jquery.com/filter/)搜索集合中的元素(顶层)。默认情况下,jqlite似乎没有定义该方法的等价物。 – 2014-10-09 15:47:41