代码之家  ›  专栏  ›  技术社区  ›  codewithian

单元测试角形及其子窗体组

  •  1
  • codewithian  · 技术社区  · 5 年前

    尝试在测试规范中生成窗体时出错。窗体生成函数还生成子窗体数组。寻找测试这个的最佳方法

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

    组件规范

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

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

    1 回复  |  直到 5 年前
        1
  •  1
  •   Athanasios Kataras    5 年前

    当你运行 detectChanges() 组件已初始化。检查以下各项:

    1. 你在经营 beforeEach it() 功能?
    2. 你为什么要还作业?何时在组件中调用buildForm函数?打电话总比重新打电话好。
    3. 什么是你的HTML。试着绑上 [FormControl] 而不是 formControlName

    单元测试的思想是引起调用各自函数的操作。

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

    您正在测试整个组件。

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

    推荐文章