无法读取属性' removeControl'未定义的Jasmine Angular4 FormControl

时间:2017-11-10 16:42:57

标签: angular unit-testing jasmine karma-jasmine

使用FormGroup Angular4我正在尝试使用formControl为删除/添加字段编写测试用例。在我的组件中使用FormGroup的removeControl()获取 TypeError:无法读取属性' removeControl'在我的测试用例中未定义

if (authType.value === 'XXX') {
  restFormGroup.removeControl('username');
} else {
  const userNameControl: FormControl = new FormControl('username', Validators.required);
  restFormGroup.addControl('username', userNameControl);
  restFormGroup.controls['password'].updateValueAndValidity();
}

我在我的测试用例中导入了表单模块,如下所示

beforeEach(async(() => {
   TestBed.configureTestingModule({
    declarations: [XXXComponent],
     imports: [
      FormsModule,
      ReactiveFormsModule,
      AppMaterialModule,
      NoopAnimationsModule
   ],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
 })
  .compileComponents()
  }));

beforeEach(() => {
   fixture = TestBed.createComponent(xxxComponent);
   component = fixture.componentInstance;
   component.xxForm = new FormGroup({});
   fixture.detectChanges();
 });

it('should be created', () => {
   expect(component).toBeTruthy();
});

我如何解决TypeError:无法读取属性' removeControl'未定义的FormGroup方法,任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

我认为您的restFormGroup未在测试用例中初始化。尝试初始化它内部的变量。像这样的东西,

// how it is initialized in the component
component.restFormGroup = new FormGroup({});