使用[[ngModel)]不会对ngFor内部的输入进行单元测试更改

时间:2018-12-06 23:19:36

标签: angular jasmine karma-jasmine

我在测试Angular组件时遇到麻烦,该组件利用[(ngModel)]内复选框输入的两种方式ngFor绑定。它在实际应用中正常工作。这只是测试的问题。

这是一个失败的示例测试:

import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { Component, EventEmitter, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';

describe('Example Test', () => {
  @Component({
    template: `
      <input *ngFor="let value of values"
             type="checkbox"
             class="checkbox-1"
             [(ngModel)]="value.isSelected"
             (change)="output.emit(values)">
    `,
    styles: [``]
  })
  class TestHostComponent {
    @Output() output: EventEmitter<any> = new EventEmitter();

    values = [
      { isSelected: true },
      { isSelected: true },
      { isSelected: true },
    ];
  }

  let testHost: TestHostComponent;
  let fixture: ComponentFixture<TestHostComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [TestHostComponent],
      providers: []
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestHostComponent);
    testHost = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should change isSelected', fakeAsync(() => {
    const spy = spyOn(testHost.output, 'emit');
    fixture.nativeElement.querySelectorAll('.checkbox-1')[0].click();
    fixture.detectChanges();
    tick();

    expect(spy).toHaveBeenCalledWith([
      { isSelected: false }, // it fails because this is still true
      { isSelected: true },
      { isSelected: true },
    ]);
  }));
});

[(ngModel)]与不在循环中的单个输入一起使用在类似的测试中效果很好。我什至已经记录了(ngModelChange)发出的值,当单击复选框时,$event应该是true时是false

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

似乎执行点击的方法不会触发更改检测。相反,在复选框上调度更改事件会产生预期的结果:

it('should change isSelected', fakeAsync(() => {
    const spy = spyOn(testHost.output, 'emit');
    const checkbox = fixture.nativeElement.querySelectorAll('.checkbox-1')[0];
    checkbox.dispatchEvent(new Event('change'));
    fixture.detectChanges();
    tick();

    expect(spy).toHaveBeenCalledWith([
        { isSelected: false }, // This is now false
        { isSelected: true },
        { isSelected: true },
    ]);
}));

this post启发的解决方案。

更新:

似乎需要等待某些控件在CheckboxControlValueAccessor上初始化或注册。如果您在创建组件后将第二个beforeEach()修改为等待一个周期,则原始测试代码有效:

beforeEach(fakeAsync(() => {
    fixture = TestBed.createComponent(TestHostComponent);
    testHost = fixture.componentInstance;
    fixture.detectChanges();
    tick();
}));

有关完整的答案/说明,请参见this Github issue

相关问题