I use one of the examples that test the "WelcomeComponent" component:
import { Component, OnInit } from '@angular/core';
import { UserService } from './model/user.service';
@Component({
selector: 'app-welcome',
template: '<h3>{{welcome}}</h3>'
})
export class WelcomeComponent implements OnInit {
welcome = '-- not initialized yet --';
constructor(private userService: UserService) { }
ngOnInit(): void {
this.welcome = this.userService.isLoggedIn ?
'Welcome ' + this.userService.user.name :
'Please log in.';
}
}
This is a test case, I am checking if "h3" contains the username "Bubba":
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { UserService } from './model/user.service';
import { WelcomeComponent } from './welcome.component';
describe('WelcomeComponent', () => {
let comp: WelcomeComponent;
let fixture: ComponentFixture<WelcomeComponent>;
let componentUserService: UserService;
let userService: UserService;
let de: DebugElement;
let el: HTMLElement;
let userServiceStub: {
isLoggedIn: boolean;
user: { name: string }
};
beforeEach(() => {
userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User' }
};
TestBed.configureTestingModule({
declarations: [WelcomeComponent],
providers: [{ provide: UserService, useValue: userServiceStub }]
});
fixture = TestBed.createComponent(WelcomeComponent);
comp = fixture.componentInstance;
userService = fixture.debugElement.injector.get(UserService);
componentUserService = userService;
userService = TestBed.get(UserService);
el = fixture.debugElement.nativeElement;
});
it('should welcome "Bubba"', () => {
userService.user.name = 'Bubba';
fixture.detectChanges();
const content = el.querySelector('h3');
expect(content).toContain('Bubba');
});
});
When testing and debugging a test case using Karma, if I evaluate "el.querySelector (" h3 ") in the console, it shows the following
<h3>Welcome Bubba</h3>
How can I get the innerHtml of the header, since it is not resolved when included in the ts file, and the test case is always false.

Here's what he says: "innerHTML" does not exist in the type "HTMLHeadingElement"
source
share