我刚开始使用ng test
来验证我的Angular应用程序。我使用Angular-Cli生成我的模块和组件,并且.spec.ts是默认的。
我在一个测试中得到了以下内容:
错误:StaticInjectorError [FormBuilder]:
StaticInjectorError [FormBuilder]: NullInjectorError:没有为FormBuilder提供程序!
它失败的组件有以下声明:
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
我的构造函数只是简单地创建了一个FormBuilder。
constructor(private fb: FormBuilder) { }
我也在我的app.module中声明了表单构建器。
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
imports: [
BrowserModule,
AdminModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
FormBuilder,
HttpModule,
NgbModule.forRoot()
测试代码
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { CreatearchiveComponent } from './createarchive.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('CreatearchiveComponent', () => {
let component: CreatearchiveComponent;
let fixture: ComponentFixture<CreatearchiveComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CreatearchiveComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CreatearchiveComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
ReactiveFormsModule
添加到您的测试模块配置中。 - Armen Vardanyan