1

I am using angular 5, always the .controls property of the form is empty. Not sure why during testing angular doesn't create the form controls by reading the template file.

Template file

<form 
  #myForm="ngForm"
  novalidate>
  <input 
    #myCtrl
    required
    type="input" 
    name="myCtrl" 
    id="myCtrl"
    [(ngModel)]="value">
</form>

Component file

@ViewChild('myForm') myForm: NgForm;

In my tests, when I console.log the following, I get {}

fixture.debugElement.componentInstance.myForm.controls

The form also has errors: null and status VALID despite the fact that the form should contain an invalid FormControl. Is it possible to unit test forms when they are configured with ViewChild rather than FormBuilder? Is there a way to do it with my ViewChild setup?

or do we have to mock the form by creating the controls again using FormGroup and assign it to

componentInstance.myForm.controls?

4

2 回答 2

4

beforeEach()尽管我在testbed.async

也使用@ViewChild('nameOfForm') sampleForm: NgForm;

当测试运行规范时,模板中指定的表单控件会被初始化并在component.sampleForm

于 2018-06-20T16:16:27.997 回答
1

我认为您需要在检查控件之前放置 fixture.detectChanges() 。

于 2018-06-16T00:01:28.567 回答