【问题标题】:Angular Unit Test: Button Click - SPEC HAS NO EXPECTATIONSAngular 单元测试:按钮单击 - 规范没有期望
【发布时间】:2020-08-10 15:13:48
【问题描述】:

我正在使用 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 没有期望单击电子邮件地址编辑按钮应该允许启用表单控制

测试尝试 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);
  }); 
}));

错误:失败:未捕获(承诺中):TypeError:无法读取 null 的属性“nativeElement” TypeError:无法读取 null 的属性“nativeElement”

资源:

Spec has no expectations - Jasmine testing the callback function

Spec has no expectation console error although expect is present

【问题讨论】:

    标签: angular typescript angular-material karma-jasmine angular8


    【解决方案1】:

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

    • 确保删除 html 中的 ngIf,或适当设置值
    • fixture.whenStable 在所有待处理的承诺都完成后返回一个承诺。这两种情况都不需要。
    • 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 中解除阻塞

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-26
      • 2017-06-28
      • 1970-01-01
      • 2021-05-09
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多