反应形式的单元测试-formBuilder上的错误

时间:2019-12-03 15:39:08

标签: angular unit-testing jasmine angular-reactive-forms

我是单元测试的新手,所以我的问题听起来有些菜鸟。 我在Angular 7中有一个反应式表单,我想进行我的第一个单元测试,但是我遇到了错误

  

TypeError:无法读取未定义的属性“ group”

我用以下方法初始化表单:

public initForms (): void {
    this.myForm = this.formBuilder.group({
        id: [tempData.id],
        firstName: [tempData.firstName],
        lastName: [tempData.lastName],
        company: [tempData.company]
    });
}

在我的测试文件中,我有:

describe('ContactListComponent', () => {
    let component: ContactListComponent;
    let fixture: ComponentFixture<ContactListComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
                CommonModule,
                ReactiveFormsModule,
                FormsModule
            ],
            providers: [ {provide:FormBuilder}]
            declarations: [ContactListComponent]
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents().then(() => {

            fixture = TestBed.createComponent(ContactListComponent);
            component = fixture.componentInstance;

            component.initForms();
       });
    }));

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

});

如果我删除component.initForms();行,则单个测试将通过,但现在我要开始实际测试

请帮助

预先感谢

1 个答案:

答案 0 :(得分:1)

从您的providers: [ {provide:FormBuilder}]通话中删除TestBed.configureTestingModule行。

FormBuilder已通过导入ReactiveFormsModule提供,因此无需再次提供。

如果确实需要覆盖提供程序,请使用此处指定的语法:https://angular.io/guide/dependency-injection-providers#the-provider-object-literal

例如:

providers: [
  FormBuilder,
  { provide: FormBuilder, useClass: OtherFormBuilder },
  { provide: FormBuilder, useExisting: OtherFormBuilder },
  { provide: FormBuilder, useValue: otherFormBuilder },
  { provide: FormBuilder, useFactory: () => otherFormBuilder }
]