首页 > 解决方案 > 单元测试 Angular 表单和 subFormGroup

问题描述

尝试在测试规范中构建表单时出错。表单构建函数还构建了一个子表单数组。寻找最好的方法来测试这个

组件.ts

buildForm() {
    return this.peopleForm = this.fb.group({
      people: this.fb.array([this.buildSubFormGroup()]),
      effective_date: [this.firstOfNextMonth(), Validators.required]
    });
  }

buildSubFormGroup(type: string = 'primary') {
    return this.fb.group({
      type: [type],
      first_name: ['', Validators.required],
      last_name: ['', Validators.required],
      dob: ['', Validators.required],
      gender: ['', Validators.required],
      uses_tobacco: ['', Validators.required],
      affordable_care: ['', Validators.required],
      is_pregnant: [''],
    });
  }

组件.spec.ts

it('should be able to build the peopleForm', () => {
    component.buildForm();
    fixture.detectChanges();
    expect(component.peopleForm.controls['type'].value).not.toBeNull();
  });

错误: 错误:没有 FormControl 实例附加到名称为“有效日期”的表单控件元素

标签: angularformsunit-testingjasminekarma-jasmine

解决方案


当您运行时detectChanges(),组件被初始化。检查以下内容:

  1. 您是否在beforeEach函数之前运行it()函数?
  2. 为什么要退回作业?什么时候在您的组件中调用 buildForm 函数?比重新运行它更好地引起调用。
  3. 你的 HTML 是什么。尝试绑定[FormControl]而不是formControlName

单元测试的想法是引起调用相应函数的动作。

示例: ngOnInit当调用 detectChanges() 时。 onClickSomething当您单击调用它的项目时,而不是通过调用 compoment.onClickSomething 函数。

您正在测试整个组件。

如需更多信息,请添加 html 和整个组件代码。


推荐阅读