禁用按钮的单元测试

Bri*_*ley 5 unit-testing jasmine karma-jasmine angular

我正在尝试为已禁用分配给布尔值的按钮编写单元测试。

html看起来像:

<button *ngIf="!data" id="createBtn" mat-button color="primary" (click)="submitNewCase()" [disabled]="disableCreate">{{ 'ACTIONS.create' | translate }}</button>
Run Code Online (Sandbox Code Playgroud)

我的单元测试:

beforeEach(() => {
 fixture = TestBed.createComponent(CaseComponent);
 component = fixture.componentInstance;
 fixture.detectChanges();
 submitEl = fixture.debugElement.query(By.css('button'));
});


  it('DisableCreate set to true disables the submit button', () => {
   component.disableCreate = true;
   fixture.detectChanges();
   expect(submitEl.nativeElement.disabled).toBeTruthy();
  });

  it('DisableCreate set to false enables the submit button', () => {
   component.disableCreate = false;
   fixture.detectChanges();
   expect(submitEl.nativeElement.disabled).toBeFalsy();
  });
Run Code Online (Sandbox Code Playgroud)

我的第二个单元测试成功,而我的第一个没有成功。我正在返回“预期为真实的错误”。我找不到失败的地方和原因。

任何帮助将非常感激。

Bri*_*ley 7

因此,将我的头撞到桌子上后,看起来好像我选择了错误的按钮。对按钮使用querySelector可以使我的测试成功。另外@Fateh Mohamed的注释设置component.data必须为null,因为按钮上有一个ngIf数据。

beforeEach(() => {
 fixture = TestBed.createComponent(CaseComponent);
 component = fixture.componentInstance;
 fixture.detectChanges();
 submitEl = fixture.debugElement
});

it('DisableCreate set to true disables the submit button', () => {
 component.disableCreate = true;
 component.data = null;
 fixture.detectChanges();
 expect(submitEl.nativeElement.querySelector('button').disabled).toBeTruthy();
});

it('DisableCreate set to false enables the submit button', () => {
 component.disableCreate = false;
 component.data = null;
 fixture.detectChanges();
 expect(submitEl.nativeElement.querySelector('button').disabled).toBeFalsy();
});
Run Code Online (Sandbox Code Playgroud)