单元测试Angular表单和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: ['',dob: ['',gender: ['',uses_tobacco: ['',affordable_care: ['',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实例

xihaibo 回答:单元测试Angular表单和subFormGroup

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

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

单元测试中的想法是使动作调用相应的功能。

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

您正在整体测试组件。

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

本文链接:https://www.f2er.com/3100925.html

大家都在问