用Jest进行Angular 9测试-为什么该mat-checkbox测试失败?

问题描述 投票:0回答:1

我的组件中有一个重置功能,可以重置所有子复选框:

  @ViewChildren('checkBoxes') checkBoxes: QueryList<MatCheckbox>;

  /**
   * Mark all checkboxes as unchecked
   */
  reset() {
    this.checkBoxes.forEach((checkbox: MatCheckbox) => {
      console.log('i am being called' + checkbox.checked);
      checkbox.checked = false;
    });
  }

这是测试:

  it('should uncheck all checkboxes when reset is called', fakeAsync(() => {
    const checkboxInput = fixture.debugElement.query(
      By.css('.mat-checkbox-input')
    );
    const el = checkboxInput.nativeElement;
    el.click();
    component.reset();
    fixture.detectChanges();
    expect(el.checked).toBe(false);
  }));

我可以从console.log中看到调用了重置功能,并且该复选框为true。但是在期望值运行的时候,当它应该为假时仍然是真的。

我尝试在tick()调用之后添加reset(),但没有区别。

UPDATE

我发现了this问题,除了他们直接更改测试内部组件上的复选框绑定属性外,该问题几乎相同。但是无论如何我都尝试过:

  it('should uncheck all checkboxes when reset is called', async(() => {
    const checkboxInput = fixture.debugElement.query(
      By.css('.mat-checkbox-input')
    );
    const el = checkboxInput.nativeElement;
    el.click();
    component.reset();
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(el.checked).toBe(false);
    });
  }));

但也失败。

angular testing jest
1个回答
0
投票

问题是时间安排之一,因此测试需要两次detectChanges

因此可行:

  it('should uncheck all checkboxes when reset is called', () => {
    const checkboxInput = fixture.debugElement.query(
      By.css('.mat-checkbox-input')
    );
    const el = checkboxInput.nativeElement;
    el.click();
    fixture.detectChanges();
    component.reset();
    fixture.detectChanges();
    expect(el.checked).toBe(false);
  });

也是这样:

  it('should uncheck all checkboxes when reset is called', async(() => {
    const checkboxInput = fixture.debugElement.query(
      By.css('.mat-checkbox-input')
    );
    const el = checkboxInput.nativeElement;
    el.click();
    fixture.detectChanges();
    component.reset();
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(el.checked).toBe(false);
    });
  }));
© www.soinside.com 2019 - 2024. All rights reserved.