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

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

第一个是空的,第二个是未定义的。

为什么?我该怎么办?

最佳答案

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

对于解决方案,您似乎在完成设置后就不会调用 fixture.detectChanges() 了,这是在您的测试中设置数据绑定(bind)所必需的。更多信息: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 - 如何在 Angular 6 中测试模板驱动的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51209570/

相关文章:

unit-testing - 单元测试功能 elisp

java - 在每个 @Test 范围之间请求新的单例 bean "WebDriver"

typescript - Angular6 - 使用名称获取嵌套 FormGroup

Angular 中的 Angular Material mat-select 动态数据绑定(bind)

javascript - 最小值和最大值的 Angular 2 表单验证

java - 需要关于用于学术研究的 Java 开源项目的推荐

arrays - 另一个数组中的数组

angular6 - 如何在 ANGULAR 6 的多级延迟加载中设置路由器

java - 在 Angular4 中渲染缩略图

javascript - 从 Javascript 调用 Grafana Angular TimePickerCtrl 函数