[英]Error: StaticInjectorError[FormBuilder] when running ng test
I have just started using ng test
to verify my Angular app. 我刚刚开始使用ng test
来验证我的Angular应用。 I used Angular-Cli to generate my modules and components and the .spec.ts were straight out of the box. 我使用Angular-Cli来生成我的模块和组件,.spec.ts是开箱即用的。
I am getting the following on one test: 我在一项测试中得到以下结果:
Error: StaticInjectorError[FormBuilder]: 错误:StaticInjectorError [FormBuilder]:
StaticInjectorError[FormBuilder]: NullInjectorError: No provider for FormBuilder! StaticInjectorError [FormBuilder]:NullInjectorError:FormBuilder没有提供者!
The component it fails on has these declared 它失败的组件已声明了这些
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
And my constructor just news up a FormBuilder 而我的构造函数只是通知一个FormBuilder
constructor(private fb: FormBuilder) { }
I also have the form builder declared in my app.module 我的app.module中也声明了表单生成器
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
imports: [
BrowserModule,
AdminModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
FormBuilder,
HttpModule,
NgbModule.forRoot()
Test code 测试码
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();
});
});
Your test uses a testing angular module which only has a CreatearchiveComponent
, but doesn't import ReactiveFormsModule. 您的测试使用的测试角度模块仅具有CreatearchiveComponent
,但不导入ReactiveFormsModule。 So the FormBuilder service, provided by ReactiveFormsModule, is not available. 因此,ReactiveFormsModule提供的FormBuilder服务不可用。 You need to import the modules that are needed by the component under test: 您需要导入被测组件所需的模块:
TestBed.configureTestingModule({
declarations: [ CreatearchiveComponent ],
imports: [ReactiveFormsModule],
schemas: [NO_ERRORS_SCHEMA]
})
Do not create formgroup instant in constructor body. 不要在构造函数主体中创建formgroup Instant。 Please create formgroup instant at top of the component class and use the same in your code. 请在组件类的顶部创建formgroup Instant,并在代码中使用相同的形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.