首页 > 解决方案 > 当我在 jasmine 单元测试中更改其模型时,mat-checkbox 不会更新检查状态

问题描述

我为材料复选框编写了一个单元测试。我使用 [(ngModule)] 将复选框绑定到模型。第一个测试用例没问题,单击复选框将更新模型但是当我在下一个单元测试中更改模型时,它不会发生。换句话说,当我将 enable 设置为 true 时,checked 状态不会更改为 true!如何通过最后的单元测试?代码上传到github

@Component({
  selector: 'app-checkbox',
  templateUrl: './checkbox.component.html'
})
export class CheckboxComponent implements OnInit {
  enabled = false;

  constructor() { }

  ngOnInit(): void {
  }

}


describe('CheckboxComponent', () => {
  let component: CheckboxComponent;
  let fixture: ComponentFixture<CheckboxComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CheckboxComponent ],
      imports: [
        MatCheckboxModule,
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CheckboxComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('click checkbox changes enabled', () => {
    const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
    expect(component.enabled).toBeFalse();
    checkBox.click();
    expect(component.enabled).toBeTruthy();
  });

  it('changing enabled will alter checkbox state', (done) => {
    const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
    component.enabled = true;
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(checkBox.checked).toBeTrue();
      done();
    });
  });
});
<mat-checkbox [(ngModel)]="enabled">Check me!</mat-checkbox>

标签: angularunit-testingangular-materialjasmine

解决方案


您很可能需要对 DOM/HTML 的新引用。checkboxfixture.detectChanges().

试试这个:

it('changing enabled will alter checkbox state', (done) => {
    const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
    component.enabled = true;
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const newCheckbox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; // grab new reference
      expect(newCheckbox.checked).toBeTrue();
      done();
    });
  });

推荐阅读