错误否定在FormControl

时间:2017-06-15 15:24:45

标签: angular jasmine karma-jasmine

我有一个Angular组件,用于编辑通过@Input()加载的对象中的数据:

export class EditFormComponent implements OnInit {

  @Input() obj: IObject;
  editForm:FormGroup;

  constructor() {}

  ngOnInit() {
    this.editForm = this.buildFormGroup();
    this.populateForm();
  }

  onClear = () => {

  };

  private buildFormGroup = ():FormGroup => {
    return new FormGroup({
      editFieldControl: new FormControl('', [])
    });
  };

  private populateForm = ():void => {
    this.editForm.controls.ediFieldControl.setValue(this.obj.field);
  }

}

该组件的模板是:

<div class="container-fluid">
  <div class="row">
    <form class="form-inline"
          [formGroup]="editForm">
      <div class="col-xl-3">
        <label for="editFieldInput"
               class="sr-only">Field Value</label>
        <input id="editFieldInput"
               type="text"
               class="form-control-sm"
               placeholder="Field"
               formControlName="editFieldControl">
      </div>
    </form>
  </div>
</div>

我使用针对我的组件修改的TestBed生成的设置来设置ng-cli

let component: EditFormComponent;
let fixture: ComponentFixture<EditFormComponent>;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ EditFormComponent ],
    imports: [ReactiveFormsModule]
  })
  .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(EditFormComponent);
  component = fixture.componentInstance;
  component.obj = {field: 'value'};
  fixture.detectChanges();
});

我可以成功测试(并失败)onInit()逻辑,因此表单控件的值将按预期设置为obj.field的值。然后我尝试生成onClear()方法的失败测试:

it('should reset FormControls to their original value', () => {
  fixture.whenStable().then(() => {
    component.editForm.controls.editFieldControl.setValue('test');
    component.onClear();
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(component.editForm.controls.editFieldControl.value).toBe(component.obj.field);
    })
  });
});

由于onClear()是一个空方法,我希望这个测试失败,但它会通过。我玩了一下,尝试失败并尝试用原来的尝试取代原来的期望失败:

expect(component.editForm.controls.editPackControl.value).toBe('111');
expect(component.editForm.controls.editPackControl.value).toBe('000');

奇怪的是,这种不可预期的期望也已经过去了。我已经尝试重新启动karma服务器,然后重新启动node本身,但是误报仍然存在。对于为什么会发生这种情况以及如何纠正它的任何想法都是值得欢迎的。

0 个答案:

没有答案