mercredi 14 avril 2021

Angular testing of mat-checkbox correctly

I'm wondering what is the correct way to test about the box checked and binded value are changed?

This is my HTML

     <div>
      <mat-checkbox class="col-md-9 text-right" id="checkid" name="checkid"
                    [checked]="this.isChecked"
                    (change)="this.isChecked = !isChecked">
        CheckBoxLabel
      </mat-checkbox>
    </div>

Then I tested by

const checkboxElem = fixture.debugElement.query(By.css('mat-checkbox')).nativeElement;
expect(checkboxElem.checked).toBeFalsy(); //pass
expect(comp.isChecked).toBeFalsy(); //pass
checkboxElem.click();
fixture.detectChanges();
expect(checkboxElem.checked).toBeTruthy(); //fail
expect(comp.isChecked).toBeTruthy(); //fail

The second expect always fails because the checkboxElem.checked=false all the time. I searched around 5 posts about the issue and have tried the following ways but none of those works:

  1. Made this test async and add whenStable(), same result
  2. Use the query By id, same result
  3. Put the text in label and defined element by fixture.debugElement.query(By.css('mat-checkbox label')).nativeElement, same result

In the debug mode, I cannot see the box of checkbox but only the label. I'm not sure how does jasmine click that element exactly.




Aucun commentaire:

Enregistrer un commentaire