如何在 angular 6 中测试模板驱动的表单

How to test template driven forms in angular 6

我有一个模板驱动的表单:

<form #form="ngForm" (ngSubmit)="onSubmit()">
      <input class="form-control input-lg" id="venue_name" name="venue_name" type="text" #venue_name="ngModel"
             [(ngModel)]="tournament.venue.venue_name" required>
      <input id="address" name="address" placeholder="search for location" required #address="ngModel"
             type="text" class="form-control input-lg" #search [(ngModel)]="tournament.venue.address">
</form>

在我的组件中,我有:

@ViewChild(NgForm) ngForm: NgForm;

在我的测试中,我有:

fixture = TestBed.createComponent(TournamentEditVenueComponent);
comp = fixture.componentInstance;
form = comp.ngForm.form;
console.log(form);

这里我可以在 Chrome 控制台中看到:

FormGroup {venue_name: FormControl, address: FormControl, details: FormControl, country_id: FormControl}

所以表格似乎可以访问

但是当我尝试用

到达它时
    console.log(form.controls);

    console.log(form.controls['venue_name']);

第一个为空,第二个未定义。

为什么?我该怎么办?

不确定这样做的确切原因 - 需要进一步研究夹具的工作原理,但下面的代码对我有用。

对于解决方案,似乎您在完成设置后不调用 fixture.detectChanges(),而这在您的测试中是设置数据绑定所必需的。更多信息:https://angular.io/guide/testing

根据此答案完成此操作后 Trying to unit test template-based form in a component, form has no controls 它说明他们到那时已修复它并确保夹具稳定 -

fixture.whenStable() returns a promise that resolves when the JavaScript engine's task queue becomes empty.

如果您尝试访问此处的表单控件,它将像下面的示例一样工作。

fixture = TestBed.createComponent(TournamentEditVenueComponent);
comp = fixture.componentInstance;
fixture.detectChanges();

fixture.whenStable().then( () => {
   console.log(comp.ngForm.controls['venue_name'])
   component.ngForm.controls['venue_name].setValue('test_venue');
})

希望对您有所帮助。