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.
query(By. css('button')); }); it('DisableCreate set to true disables the submit button', () => { component. disableCreate = true; fixture. detectChanges(); expect(submitEl.
fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement. textContent.
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();
});
Found another way,
in your HTML add id to button, i.e
<button id="myButtonId" [disabled]="someCondition">/<button>
in test file get the button (by id or any other way) and check disabled state by ng-reflect-disabled attribute
const addButton = fixture.debugElement.nativeElement.querySelector('#myButtonId');
expect(addButton.attributes.getNamedItem('ng-reflect-disabled').value).toBeTruthy();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With