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

时间:2018-07-06 11:35:19

标签: angular testing angular6

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

<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']);

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

为什么?我该怎么办?

1 个答案:

答案 0 :(得分:10)

不确定确切原因-需要研究灯具的工作原理,但是下面的代码对我有用。

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

一旦根据答案Trying to unit test template-based form in a component, form has no controls完成了此操作,它说明他们在修复此问题的同时还确保了夹具的稳定性-

  

fixture.whenStable()返回一个承诺,当   JavaScript引擎的任务队列为空。

如果您尝试在此处访问表单控件,则它将如以下示例所示工作。

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');
})

希望这会有所帮助。