问题描述
我的观点是这样的
<div>
<div class="header-title">Example title 1</div>
</div>
<div>
<div class="header-title">Example title 2</div>
</div>
在业力测试中,我想按类名称调查所有div,并检查内部文本是否正确,因此我在测试中有以下代码:
In my karma test I would like to investigate all divs by class name and check if inner text is correct so I have following code in test:
[...]
debugTest = fixture.debugElement.query(By.css('.header-title'));
elementTest = debugTest.nativeElement;
[...]
it('should component div has a correct value', () => {
fixture.detectChanges();
const content = elementTest.textContent;
expect(content).toContain('Example Title 1');
});
以下代码可以工作,但我总是通过.header-title类获得第一个dom.如何提取下一个?如果我有20个具有相同类名的div怎么办?
Following code works but I always get the first dom with .header-title class. How to extract next one? What if I have 20 divs with the same class name how to test them all?
推荐答案
使用queryAll()
代替query()
,这将返回一个数组.
Use queryAll()
instead of query()
, which returns an array.
query()
返回单个DebugElement
,它始终是第一个匹配的元素,而queryAll()
返回DebugElement[]
.
query()
returns single DebugElement
which is always the first matching element, whereas queryAll()
returns DebugElement[]
.
debugTest = fixture.debugElement.queryAll(By.css('.header-title'));
这样您就可以访问
elementTest1 = debugTest[0].nativeElement;
elementTest2 = debugTest[1].nativeElement;
这篇关于在业力测试中按类名获取两个div(Angular 4.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!