Search code examples
angularunit-testingjasminekarma-jasmine

Unit test for Button with disable


I am trying to write a unit test for a button that has disabled assigned to a boolean.

html looks like:

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

my unit test:

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();
  });

My second unit test succeeds and my first one does not. I am getting back a "Expected false to be truthy.". I cannot find where this is failing and why.

Any help would be much appreciated.


Solution

  • So after banging my head against the table a little longer it looks like I was selecting the button incorrectly. Using querySelector for button has my test succeeding. Also to @Fateh Mohamed's comment setting component.data to null is required since there is a ngIf for data on the button.

        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();
        });