正如 Angular.io 框架测试文档所建议的,我一直在尝试使用 Angular Testbed + Karma 测试运行器来使用 DebugElement 查询。我创建了一个 jqwidgets Tree 组件,它生成类 '.jqx-tree-item-li' 的 li 元素。以下在 DOM 测试中直接使用 javascript 的测试通过了 GREEN:
it('Elements of class jqx-tree-item-li found using getElementsByClassName ', (done) => {
this.fixture.whenStable().then(
() => {
var elementArray = document.getElementsByClassName('jqx-tree-item-li');
expect(elementArray.length).toBeGreaterThan(0); //passes without issue :)
done();
}
);
});
但此测试在SAME 规范(相同的测试平台设置)中失败,因为返回了 0 个元素:
it('Elements of class jqx-tree-item-li found using Angular DebugElement ', (done) => {
this.fixture.whenStable().then(
() => {
var elementArray = this.fixture.debugElement.queryAll(By.css('.jqx-tree-item-li'));
expect(elementArray.length).toBeGreaterThan(0); //fails! why? :(
done();
}
);
});
Object Explorer Component Elements of class jqx-tree-item-li found using Angular DebugElement Expected 0 to be greater than 0.
这不是我第一次观察到这一点,我发现它会获取根组件元素,但我似乎无法获取 DebugElement 查询以返回组件内的元素。尽管文档明确指出它将查询子树。到目前为止,解决方法只是像上面那样按预期运行的 javascript 查询。
我是不是漏掉了什么?关于如何让 DebugElement.query 工作的任何建议?如果没有,是否有人发现 DebugElement 查询有问题?谢谢。
最佳答案
你犯了几个错误
detectChanges
丢失通过
document
查询是错误的,你应该使用fixture.debugElement
it('Elements of class jqx-tree-item-li found using getElementsByClassName ', (done) => { this.fixture.whenStable().then( () => { fixture.detectChanges(); // missed var elementArray = fixture.debugElement.query(By.css('.jqx-tree-item-li')); // use fixture instance to expect(elementArray.length).toBeGreaterThan(0); //passes without issue :) done(); } ); });
关于javascript - 按类不返回元素的 Angular Fixture DebugElement 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45517618/