为什么选中的复选框 属性 在 detectChanges() 之后没有改变

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

我尝试通过更改模型来更改选中的复选框 属性,但它不起作用。我无法理解这种行为。

模板:

<input type="checkbox" [(ngModel)]="model"/>

测试代码:

    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();
    });

完整代码:https://stackblitz.com/edit/angular-testing-checkbox?file=app/app.component.spec.ts

因为angular变化检测是异步的。您的 expect() 语句在 detectChanges() 之前执行。在这种情况下使用 angular 测试 async() 函数:

   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();
        })   
    }));

您可以将 fixture.whenStabledone 函数一起使用,以将异步更改检测周期与 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();
    });
});