如何在角度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');
})

希望这可以帮助.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...