Why checkbox checked property doesn't change after detectChanges()

一个人想着一个人 提交于 2021-01-29 04:00:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!