I am accessing Markup from a child component using fixture.
await TestBed.configureTestingModule({
declarations: [MyComponent, MyChildComponent],
imports: [
MatChipsModule,
],
}).compileComponents();
fixture = TestBed.createComponent(MyComponent);
const chips = fixture.debugElement.queryAll(By.css('mat-chip'));
expect(chips.length).toBe(2); // works fine
If i print that markup, it shows content, but if i try to access innerText/innerHtml, boith are undefined.
console.log(chips[0].nativeElement);
prints
<mat-chip aria-disabled="false" aria-selected="true" class="mat-chip mat-focus-indicator mat-primary mat-standard-chip mat-chip-selected" color="primary" ng-reflect-color="primary" ng-reflect-selected="" role="option" selected="" tabindex="-1">
<div class="mat-chip-ripple" />
1
</mat-chip>
but
console.log(chips[0].nativeElement.innerText);
console.log(chips[0].nativeElement.innerHtml);
both print undefined
while it should print the <div>
and/or the 1
You can try using textContent
for looking at the content of the tag as plain text. It’s most effective when you want to see what’s in an element, plus styling.
const element = fixture.debugElement.query(By.css('#myDiv'));
const value = element.nativeElement.textContent;
expect(value).toBe('some value');
I think the reason for using textContent
when testing is because of the debugElement
, since the DOM could be seen as an API for manipulating the HTML, we only have access to textContent.
In any case, when it comes to testing with Angular, I recommend this site, it helped me to have a better understanding of how testing works and how to use it with Angular.