我正在使用其中一个测试组件的示例' WelcomeComponent':
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.';
}
}
这是测试用例,我正在检查&#39; h3&#39;包含用户名&#39; Bubba&#39;:
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; // the actually injected service
let userService: UserService; // the TestBed injected service
let de: DebugElement; // the DebugElement with the welcome message
let el: HTMLElement; // the DOM element with the welcome message
let userServiceStub: {
isLoggedIn: boolean;
user: { name: string }
};
beforeEach(() => {
// stub UserService for test purposes
userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User' }
};
TestBed.configureTestingModule({
declarations: [WelcomeComponent],
// providers: [ UserService ] // NO! Don't provide the real service!
// Provide a test-double instead
providers: [{ provide: UserService, useValue: userServiceStub }]
});
fixture = TestBed.createComponent(WelcomeComponent);
comp = fixture.componentInstance;
// UserService actually injected into the component
userService = fixture.debugElement.injector.get(UserService);
componentUserService = userService;
// UserService from the root injector
userService = TestBed.get(UserService);
// get the "welcome" element by CSS selector (e.g., by class name)
el = fixture.debugElement.nativeElement; // de.nativeElement;
});
it('should welcome "Bubba"', () => {
userService.user.name = 'Bubba'; // welcome message hasn't been shown yet
fixture.detectChanges();
const content = el.querySelector('h3');
expect(content).toContain('Bubba');
});
});
使用Karma测试和调试测试用例时,如果我在控制台中评估&#34; el.querySelector(&#39; h3&#39;),则会显示以下内容
<h3>Welcome Bubba</h3>
如何,我可以获得标题的innerHtml,因为当它包含在ts文件中并且测试用例总是评估为false时它没有解决。
这就是它所说的:&#39; innerHTML&#39;不存在类型&#39; HTMLHeadingElement &#39;
答案 0 :(得分:14)
这是因为content
const content = el.querySelector('h3');
expect(content).toContain('Bubba');
是HTMLNode
,而不是原始文本。所以你期望HTMLNode
成为一个字符串。这将失败。
您需要使用content.innerHTML
或content.textContent
提取原始HTML(以获取<h3>
代码之间的内容
const content = el.querySelector('h3');
expect(content.innerHTML).toContain('Bubba');
expect(content.textContent).toContain('Bubba');