Search code examples
angularformsjasmineangular-formsangular-test

testing angular template driven forms


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?


Solution

  • I was missing async in beforeEach(), though I had the testbed configuration in async.

    Also use @ViewChild('nameOfForm') sampleForm: NgForm;

    while the test runs the spec, the form controls specified in the template does gets initialized and available in component.sampleForm