【发布时间】:2023-04-03 10:00:01
【问题描述】:
我的任务是为使用 Angular 开发的聊天应用程序编写测试。以下是我目前正在为其编写测试的 Angular 模板代码的 sn-p:
<div class="title-menu-container" fxLayoutAlign="center center">
<button id="save-title-button" mat-icon-button *ngIf="titleInputEdit; else settings">
<mat-icon class="secondary-text" (click)="saveTitle(titleInput.value)">check</mat-icon>
</button>
<ng-template #settings>
<button mat-icon-button [matMenuTriggerFor]="menu" [disabled]="!(isGroupConversation$ | async)">
<mat-icon class="secondary-text">settings</mat-icon>
</button>
</ng-template>
</div>
本质上,如果组件布尔变量'titleInputEdit'为真,则显示保存标题按钮,否则显示设置按钮。这是导致问题的测试用例:
it('save title button should be present', () => {
component.titleInputEdit = true;
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#save-title-button')).not.toBe(null);
});
我只是“模拟”组件变量,调用 .detectChanges(),然后测试按钮是否存在。但是,测试失败并显示“预期 null 不为 null”。
通过各种 console.log 调用,我确认 component.titleInputEdit 已正确设置为 true,但 fixture.nativeElement 不包含正确的按钮。
我注意到的一些事情:
-
如果我将 'component.titleInputEdit = true' 行移到我的 beforeEach 中并将其删除,并且从我的测试中调用 detectChanges(),则测试通过。
beforeEach(() => { fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; component.titleInputEdit = true fixture.detectChanges(); debugElement = fixture.debugElement; }); it('save title button should be present', () => { expect(fixture.nativeElement.querySelector('#save-title-button')).not.toBe(null); }); 如果我从 beforeEach() 中删除 .detectChanges() 调用,并将其留在测试用例中,则测试通过。
我对 Angular 比较陌生,但我发现有人遇到类似问题。在尝试了这些帖子中推荐的一些东西之后,我仍然摸不着头脑。更奇怪的是,我已经为其他 Angular 组件编写了测试,这些组件几乎可以毫无问题地做同样的事情。
Angular 文档中提供的示例也显示了非常相似的内容:
it('should display a different test title', () => {
component.title = 'Test Title';
fixture.detectChanges();
expect(h1.textContent).toContain('Test Title');
});
【问题讨论】:
-
这能回答你的问题吗? Testing OnPush components in Angular 2