【问题标题】:How to test template driven forms in angular 6如何在 Angular 6 中测试模板驱动的表单
【发布时间】:2018-07-06 11:35:19
【问题描述】:

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

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

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

为什么?我该怎么办?

【问题讨论】:

    标签: angular testing angular6


    【解决方案1】:

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

    对于一个解决方案,您似乎在完成设置后就不会调用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');
    })
    

    希望这会有所帮助。

    【讨论】:

    • 您如何访问comp.ngForm。它不会像那样直接访问
    • 为了避免测试用例中出现回调地狱,您可以在测试集中放入beforeEachawait fixture.whenStable();。这样,您的所有测试都将保持稳定,并且您的角度形式将被加载
    猜你喜欢
    • 2019-06-29
    • 2018-11-25
    • 1970-01-01
    • 2017-01-30
    • 2016-04-26
    • 2019-01-20
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    相关资源
    最近更新 更多