问题
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
回答1:
Because angular change detection is asynchronous. Your expect()
statement happenned before change dectection is finished. Use angular testing async()
function in your test :
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();
})
}));
回答2:
You could use fixture.whenStable
together with the done
function to synchronize the asynchronous change detection cycle with the expect
.
it('should be checked after click on unchecked checkbox', (done) => {
const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');
component.model = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(checkbox.checked).toBe(true);
done();
});
});
来源:https://stackoverflow.com/questions/58818537/why-checkbox-checked-property-doesnt-change-after-detectchanges