Angular 单击按钮后单元测试 ng-template 触发器不起作用

Angular Unit test ng-template trigger after button click not working

我正在尝试获取 ng-template 中按条件可见的元素,但它不起作用,我收到错误消息“Expected false to equal true”。

<ng-template #staticDataTemplate>
  <div class="static-data-container">
    Static field goes here...
    <button class="edit-button" (click)="showEditableData()">Edit</button>
  </div>
</ng-template>

<ng-template #editableDataTemplate>
  <div class="editable-data-container">
    editable form goes here...
  </div>
</ng-template>

  <ng-container *ngIf="!editing">
    <ng-container *ngTemplateOutlet="staticDataTemplate"></ng-container>
  </ng-container>
  <ng-container *ngIf="editing">
    <ng-container *ngTemplateOutlet="editableDataTemplate"></ng-container>
  </ng-container>

我的component.ts就像

showEditableData(){
  this.editable = true;
}

还有我的component.spec.ts

 it('should enable editing form', fakeAsync(() => {

    const queryStaticContainer = fixture.debugElement.query(By.css('.static-data-container'));
    const isStaticContainerShown = () => !!queryStaticContainer();

    const queryEditableContainer = fixture.debugElement.query(By.css('.editable-data-container'));
    const isEditableContainerShown = () => !!queryEditableContainer();

    expect(isStaticContainerShown()).toEqual(true);
    expect(isEditableContainerShown()).toEqual(false);
    fixture.detectChanges();

    const buttonEdit = fixture.debugElement.query(By.css('.edit-button'));
    buttonEdit.triggerEventHandler('click', null);

    fixture.detectChanges();
    fixture.whenStable();

    expect(isEditableContainerShown()).toEqual(true); //here where the error shown
    expect(component.editing).toBeTrue();
  }));

显然,按钮触发器不起作用,因此模板在 dom 中不可见,那么如何才能使模板可见?

你可以试试打电话 fixture.debugElement.query(By.css('.editable-data-container')) 按钮点击之后而不是之前

我还会在 beforeEach 块 before it 块中单击按钮和 fixture.detectChanges()

您还可以 console.log(fixture.nativeElement.innerHTML) 准确查看正在渲染的内容。