【问题标题】:Cannot read property 'removeControl' of undefined Jasmine Angular4 FormControl无法读取未定义 Jasmine Angular4 FormControl 的属性“removeControl”
【发布时间】:2018-04-23 23:02:41
【问题描述】:

使用 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: Cannot read property 'removeControl' of undefined of FormGroup 方法,任何帮助都会很棒。

【问题讨论】:

  • 你的因果代码?
  • 它只是创建组件测试用例。我是否应该为 removeControl() 方法在 formGroup 组件上添加一个间谍我不知道...刚刚更新了上面的代码
  • 你的 restFormGroup 还不能有一个名为 'username' 的控件。你是在组件中创建这个表单控件oninit吗?
  • @Karthigeyan 您可以监视和断言测试用例。记得在it 内触发fixture.detectChanges() 而不是beforeEach()
  • @Z.Bagley 是的,我正在根据下拉表单 valueChanges 条件在 OnInit 上创建此表单字段

标签: angular unit-testing jasmine karma-jasmine


【解决方案1】:

我认为你的 restFormGroup 没有在测试用例中初始化。尝试初始化其中的变量。像这样的,

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

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多