Angular 7测试:“无法绑定到formGroup,因为它不是form的已知属性”

时间:2019-02-15 16:53:53

标签: angular unit-testing karma-jasmine

控制台记录错误:

  

15 02 2019 14:50:24.868:INFO [Chrome 72.0.3626(Windows 10.0.0)]:   已通过ID 27946068 Chrome连接到插座BiEioS9fHwq-QLg3AAAA   72.0.3626(Windows 10.0.0)LoginComponent应该创建FAILED           无法绑定到“ formGroup”,因为它不是“ form”的已知属性。 (“

        <div class="row">
     

(等)

我正在使用命令ng test运行它。我的规格文件:

describe('LoginComponent', () => {

    let component: LoginComponent;
    let fixture: ComponentFixture<LoginComponent>;

    const fakeActivatedRoute = {
        snapshot: { data: {} }
    } as ActivatedRoute;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                LoginComponent
            ],
            imports: [
                RouterTestingModule,
                HttpClientModule,
                CommonModule,
                BrowserModule,
                BrowserAnimationsModule,
                ReactiveFormsModule,
                MessageModule,
                MatFormFieldModule,
                MatInputModule,
                MatButtonModule,
                MatCheckboxModule,
                MatProgressSpinnerModule,
                MatRadioModule,
                MatSliderModule,
                NgbModule
            ],
            providers: [
                {
                    provide: ActivatedRoute,
                    useValue: fakeActivatedRoute
                }
            ]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.debugElement.componentInstance;
        fixture.detectChanges();
    });

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

});

还有LoginModule文件:

@NgModule({
  declarations: [LoginComponent],
  imports: [
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatCheckboxModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatSliderModule,
    MessageModule,
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [
    LoginComponent,
    MessageComponent
  ]
})
export class LoginModule {}

缺少什么?

3 个答案:

答案 0 :(得分:2)

您需要将componentName.spec.ts文件中的ReactiveFormsModule导入为

import { ReactiveFormsModule } from '@angular/forms';
beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [ ContactUsFormComponent ],
  imports: [ReactiveFormsModule]
})
.compileComponents();}));

答案 1 :(得分:0)

类似于Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

我认为您缺少在configureTestingModule中导入FormsModule

答案 2 :(得分:0)

我认为是

FormsModule

.forRoot()

在测试导入的NgbModule中。