I have something like this in view:
<div>
<div class="header-title">Example title 1</div>
</div>
<div>
<div class="header-title">Example title 2</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 ponent div has a correct value', () => {
fixture.detectChanges();
const content = elementTest.textContent;
expect(content).toContain('Example Title 1');
});
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?
I have something like this in view:
<div>
<div class="header-title">Example title 1</div>
</div>
<div>
<div class="header-title">Example title 2</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 ponent div has a correct value', () => {
fixture.detectChanges();
const content = elementTest.textContent;
expect(content).toContain('Example Title 1');
});
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?
Share Improve this question edited Mar 21, 2018 at 5:00 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Mar 20, 2018 at 7:26 KacpersKacpers 1933 silver badges7 bronze badges1 Answer
Reset to default 11Use queryAll()
instead of query()
, which returns an array.
query()
returns single DebugElement
which is always the first matching element, whereas queryAll()
returns DebugElement[]
.
debugTest = fixture.debugElement.queryAll(By.css('.header-title'));
So that you can access like
elementTest1 = debugTest[0].nativeElement;
elementTest2 = debugTest[1].nativeElement;