【问题标题】:Why checkbox checked property doesn't change after detectChanges()为什么在detectChanges()之后复选框选中的属性没有改变
【发布时间】:2020-03-08 03:42:27
【问题描述】:

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

模板:

<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 jasmine angular-test


    【解决方案1】:

    因为角度变化检测是异步的。您的expect() 语句在detectChanges() 之前执行。在这种情况下使用角度测试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();
            })   
        }));
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2014-11-24
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-15
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        相关资源
        最近更新 更多