I have structured my form field abstraction in a way that works in development but not in my unit test.
// required.control.ts
import { FormControl, Validators } from '@angular/forms';
export class RequiredControl extends FormControl {
protected textErrors: { [key: string]: string } = {
required: 'Mandatory field'
};
constructor(value: string | any = '') {
super(value);
this.setValidators([Validators.required]);
}
get textError() {
let message = '';
for (const error in this.textErrors) {
if (error && this.hasError(error) && this.dirty) {
message = this.textErrors[error];
return message;
}
}
return message;
}
get state() {
return this.valid || !this.dirty ? '' : 'error';
}
}
To streamline my form and separate the validation logic for each field, I import this file into my main component:
// my-component.component.ts
import { RequiredControl } from './required.control.ts';
@Component({})
export class MyComponent implements OnInit { // I skiped import for this OnInit
reasonControl = new RequiredControl(null);
constructor() {}
ngOnInit() {
this.requestForm = this.formBuilder.group({
reason: this.reasonControl, // first method tried :(
reason:this.reasonControl as FormControl, // second method tried :(
});
}
}
During my unit tests, I include the following setup:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [ReactiveFormsModule, FormsModule, RouterTestingModule]
})
}));
The template includes:
https://i.sstatic.net/NDBeM.png
Running the test results in the following error: