我刚开始使用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();
});
});
答案 0 :(得分:5)
您的测试使用的测试角度模块只有CreatearchiveComponent
,但不会导入ReactiveFormsModule。因此,ReactiveFormsModule提供的FormBuilder服务不可用。您需要导入被测组件所需的模块:
TestBed.configureTestingModule({
declarations: [ CreatearchiveComponent ],
imports: [ReactiveFormsModule],
schemas: [NO_ERRORS_SCHEMA]
})
答案 1 :(得分:0)
不要在构造函数主体中创建formgroup即时。请在组件类的顶部创建formgroup Instant,并在您的代码中使用它。