单元测试 Angular 窗体和子窗体组

Unit test Angular form and subFormGroup

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

component.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: [''],
    });
  }

component.spec.ts

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

错误: 错误:没有 FormControl 实例附加到名称为 'effective_date'

的表单控件元素

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

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

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

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

您正在对组件进行整体测试。

有关详细信息,请添加 html 和整个组件代码。