Angular e2e - 应该在 h1 标签中呈现标题

Angular e2e - should render title in a h1 tag

我正在开发自己的网站。我是 Angular 的新手,基于学习和在线帖子,我开始开发我的网站。 运行 测试时,我在获取 h1 标签值时遇到错误。

我开发了路线。 AppComponent加载的路由之一是HomeComponent,其中有h1标签。

在app.component.spec.ts文件中,下面是获取h1值失败。

it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to jc-web!');});

谁能建议我如何在上面的代码中从 HomeComponent 获取 h1 值?

感谢您的帮助。

为了访问嵌套在 AppComponent 中的 HomeComponent 中的 h1 值,您需要在 TestBed 中提供实际的 HomeComponent:

TestBed.configureTestingModule({
    declarations: [
        AppComponent,
        HomeComponent
    ]
});

或者提供一个存根版本供您的测试使用。如果您选择提供实际组件,您还必须包括它的所有依赖项。 Angular 文档 here.

中有关于如何测试嵌套组件的更详细说明

您只需要在app.component.ts文件中添加以下代码即可。

标题='the title';

app.component.spec.ts app.component.ts

您需要在 2 个文件中进行更改,代码才能正常工作。