问题
I have a PhoneNumbersFormComponent
whose template looks like :
<div [formGroup]="form">
<div formArrayName="numbers">
<input formControlName="countryPrefix">
<input formControlName="number">
</div>
</div>
I want to pass the default test created by angular-cli's ng g component xxx
The first error I got was:
Cannot find control with name 'countryPrefix'
Which I solved with:
beforeEach(() => {
fixture = TestBed.createComponent(PhoneNumbersFormComponent);
component = fixture.componentInstance;
component.phoneNumbers = [];
component.form = new FormGroup({
countryPrefix: new FormControl(),
number: new FormControl()
});
fixture.detectChanges();
});
Now the last remaining error is:
Cannot find control with name 'numbers'
And I have no idea how to test formArrayName="numbers"
回答1:
Try something like this:
let array: FormGroup[] = [];
array.push(new FormGroup({
countryPrefix: new FormControl(),
number: new FormControl()
}));
let formArray = new FormArray(array);
component.form = new FormGroup({
numbers: formArray // or array not totally sure
})
回答2:
Alternatively you can build a FormArray in your component and provide a getter for the form array.
ngOnInit() { this.formArrayOfPhoneNumbers = this.phoneNumbers.map((phone) =>
{ return new FormGroup({ countryPrefix: [phone.countryPrefix], number: [phone.number] })
}
get numbers: FormArray { return this.formArrayOfPhoneNumbers as FormArray }
I'm not exact on the syntax most likely, but the point is that the formArrayName directive will call the getter and you can ensure that a FormArray object is being returned.
来源:https://stackoverflow.com/questions/46723685/testing-formarray