Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法读取未定义的Jasmine Angular4 FormControl的属性“removeControl”_Angular_Unit Testing_Jasmine_Karma Jasmine - Fatal编程技术网

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

无法读取未定义的Jasmine Angular4 FormControl的属性“removeControl”,angular,unit-testing,jasmine,karma-jasmine,Angular,Unit Testing,Jasmine,Karma Jasmine,使用FormGroup Angular4,我正在尝试使用formControl为remove/add字段编写测试用例。在我的组件中使用FormGroup的removeControl TypeError:无法读取测试用例中未定义的属性“removeControl” if (authType.value === 'XXX') { restFormGroup.removeControl('username'); } else { const userNameControl: FormContr

使用FormGroup Angular4,我正在尝试使用formControl为remove/add字段编写测试用例。在我的组件中使用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:无法读取FormGroup方法的undefined的属性'removeControl',任何帮助都会很好。

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

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

您的karma代码?它只是创建组件测试用例。。我不知道是否应该为removeControl方法添加一个spy on formGroup组件。。。刚刚更新了上面的代码您的restFormGroup还不能有名为“username”的控件。您是否在组件中创建此表单控件oninit?@Karthigeyan您可以监视并断言测试用例。记住触发fixture.detectChanges,而不是beforeEach@Z.Bagley是,我正在基于下拉表单值更改条件在OnInit上创建此表单字段