I try to change checkbox checked property by changing model but it doesn't work. I cannot understand this behavior.
Template:
<input type="checkbox" [(ngModel)]="model"/>
Testing Code:
it('should be checked after click on unchecked checkbox', () => {
const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');
component.model = true;
fixture.detectChanges();
expect(checkbox.checked).toBeTruthy();
});
Full code: https://stackblitz.com/edit/angular-testing-checkbox?file=app/app.component.spec.ts
Because angular change detection is asynchronous. Your expect()
statement is executed before detectChanges()
. Use angular testing async()
function for this case:
it('should be checked after click on unchecked checkbox', async( () => {
const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');
component.model = true;
fixture.detectChanges();
fixture.whenStable().then(()=> {
expect(checkbox.checked).toBeTruthy();
})
}));