【发布时间】:2022-01-12 05:09:44
【问题描述】:
我正在从我的表单中抽象出每个字段,如下所示(这在开发中有效,但在我的单元测试中无效)
// 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';
}
}
这样我可以清理我的表单并将每个字段的验证逻辑带到一个单独的文件中。现在,在主组件中,我导入了这个文件:
// 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 :(
});
}
}
在我的单元测试中,我有以下内容:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [ReactiveFormsModule, FormsModule, RouterTestingModule]
})
}));
我的模板中有这个:
当我运行此测试时,我收到以下错误:
【问题讨论】:
标签: angular typescript unit-testing form-control controlvalueaccessor