'How to write test case for @viewchild element referenced for input type checkbox in angular 8?

I am new to angular test case. I have a input type checkbox which has element ref id of #checkbox. Below is code snippet. How to write test case for masterToggle function in below code? If anyone know please help to find the solution.

app.component.ts:

@ViewChild('checkbox') checkbox;

function masterToggle(){
this.checkbox.nativeElement.checked = false;
this.checkbox.nativeElement.indeterminate = false;
}

HTML :

<input type="checkbox" class="nodecheckbox" #checkbox [disabled]="isCheckboxDisabledForSelectAll()" (change)="masterToggle(data)" >


Solution 1:[1]

The purpose of testing is to verify, if a functionality is behaving accordingly to the dev expectation. Starting from here we should test if masterToggle method sets checked property to false and indeterminate to false.

Inside a test file in Angular you have access to all public methods, and eventually by using bracket notation(Mycomponent[privateMethodOrPropertyName]). So this actually allows you for easy testing.

it('should be ok', async(() => {
    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      let checkbox = fixture.debugElement.query(/*you should locate yourcheckbox*/);

      component.masterToggle();
      // if model doesn't update use fixture.detectChanges();

      expect(checkbox.nativeElement.checked).toBe(False);
      expect(checkbox.nativeElement.indeterminate).toBe(False);
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Filas Siuma