Angular 单元测试:按钮点击 - 规格没有预期

Angular Unit Test: Button Click - SPEC HAS NO EXPECTATIONS

我是 运行 Karma Jasmine 的 Angular 单元测试。它正在测试按钮输入。我们收到了以下两项测试的说明,一项是常规测试,一项是异步测试。

有谁知道如何修复这个单元测试?组件中的其他测试 运行 成功。

HTML:

<div *ngIf="enableButtonFlag">
    <button class="email-edit-button" mat-icon-button (click)="editSharedFormControl('emailAddress')">
        <mat-icon>edit</mat-icon>
    </button>
</div>

测试尝试 1:

it('click emailAddress Edit button should allow form control enabled', ()=> {

fixture.whenStable().then(() => {
  let button = fixture.debugElement.query(By.css('.email-edit-button')).nativeElement;
  button.click();
  tick();
  fixture.detectChanges();
  expect(component.editSharedForm.get('emailAddress').enabled).toBe(true);
  });
});

结果:测试没有失败或成功:

SPEC HAS NO EXPECTATIONS click emailAddress Edit button should allow form control enabled

测试尝试 2:异步

it('click emailAddress Edit button should allow form control enabled', async (()  => {

fixture.whenStable().then(() => {
  let button = fixture.debugElement.query(By.css('.email-edit-button')).nativeElement;
  button.click();
  tick();
  fixture.detectChanges();
  expect(component.editSharedForm.get('emailAddress').enabled).toBe(true);
  }); 
}));

Error: Failed: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of null TypeError: Cannot read property 'nativeElement' of null

资源:

对于测试#1 和测试#2:

  • 确保删除 html 中的 ngIf,或适当设置值
  • fixture.whenStable returns 当所有待处理的承诺都已完成时的承诺。这两种情况都不需要。
  • tick 的概念仅在测试 运行 以 fakeAsync 方式存在时才存在。它不在这里,所以它什么都不做。

尝试:

it('should display emailEdit button', () => {
  // make the requirements to make sure .email-edit-button will be present in the view
  // in essence, it is not blocked by an *ngIf
  fixture.detectChanges();
  const button = fixture.debugElement.query(By.css('.email-edit-button'));
  console.log(button); // see what this logs, make sure it is truthy and a button
  expect(button).not.toBeNull();
});

it('click emailAddress Edit button should allow form control enabled', ()  => {
  // make the requirements to make sure .email-edit-button will be present in the view
  // in essence, it is not blocked by an *ngIf 
  fixture.detectChanges();
  let button = fixture.debugElement.query(By.css('.email-edit-button')).nativeElement;
  button.click();
  fixture.detectChanges();
  expect(component.editSharedForm.get('emailAddress').enabled).toBe(true);
});

如果你通过了第一个测试(it should display emailEdit button),第二个测试应该从Cannot read property 'nativeElement' of null

中解锁