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?

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

I think you need to put fixture.detectChanges() prior to checking for the controls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.