如何在角度6中测试模板驱动的表格

Jul*_*oro 5 testing angular 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>
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我有:

@ViewChild(NgForm) ngForm: NgForm;
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我有:

fixture = TestBed.createComponent(TournamentEditVenueComponent);
comp = fixture.componentInstance;
form = comp.ngForm.form;
console.log(form);
Run Code Online (Sandbox Code Playgroud)

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

FormGroup {venue_name: FormControl, address: FormControl, details: FormControl, country_id: FormControl}
Run Code Online (Sandbox Code Playgroud)

所以表格似乎是可以达到的

但当我试图与它达成时

    console.log(form.controls);
Run Code Online (Sandbox Code Playgroud)

要么

    console.log(form.controls['venue_name']);
Run Code Online (Sandbox Code Playgroud)

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

为什么?我应该怎么做?

小智 12

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

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

基于此答案完成此操作尝试在组件中单元测试基于模板的表单,表单没有控件,它解释了他们修复它然后还确保灯具稳定 -

fixture.whenStable()返回一个在JavaScript引擎的任务队列变空时解析的promise.

如果您尝试访问此处的表单控件,那么它将在下面的示例中工作.

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');
})
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 为了避免测试用例中的回调地狱,您可以在测试集中放置一个带有“await Fixture.whenStable();”的“beforeEach”。这样你的所有测试都会稳定并且你的角度形式将被加载 (2认同)