【问题标题】:Unit test in reactive form - error on formBuilder反应形式的单元测试 - formBuilder 上的错误
【发布时间】:2019-12-04 00:36:04
【问题描述】:

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

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

我用以下方式初始化我的表单:

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(); 单个测试将通过,但现在我想开始真正的测试

请帮忙,

提前致谢

【问题讨论】:

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


    【解决方案1】:

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

    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 }
    ]
    

    【讨论】:

    • 谢谢@Alex k。我从提供者中删除了 FormBuilder 并解决了我的问题。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2020-08-25
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多