【问题标题】:Angular Unit Test: Error: No value accessor for form control角度单元测试:错误:表单控件没有值访问器
【发布时间】: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


    【解决方案1】:

    我为我的问题找到了正确的解决方案,在输入元素中使用 ngDefaultControl,如下所示:

    此属性为测试提供了必要的知识,以便能够在第三方组件中将此元素识别为FormControl(就像我的情况一样)。添加该属性可以解决问题。

    【讨论】:

    • 我认为这不是处理这个问题的正确方法。如果您使用任何 3rd 方组件,您也应该在单元测试中导入它或模拟它。
    • 我试过了,但这对我来说是不可能的,而且我在测试中表现良好,并且表单控件具有正确的值。
    • 使用此解决方案,您添加了一些代码,这些代码仅用于处理不正确的单元测试用例。如果您可以创建一个 stackblitz 示例,我们可以提供帮助。
    • 好的,谢谢
    猜你喜欢
    • 2020-10-22
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多