由于服务出现 NullInjector 错误,我的 Karma 测试失败。
- 服务正在组件中工作(测试有问题,而不是组件有问题?),
- 服务注入(inject)适用于其他组件,并且它们的测试通过
类似问题的解决方案与声明提供者有关。就我而言,我已经声明了一个提供者(见下文),并且该服务在组件内部工作。
Error: StaticInjectorError[LoginComponent -> AuthenticationProvider]:
NullInjectorError: No provider for AuthenticationProvider!
服务:
@Injectable()
export class AuthenticationProvider {
uri: string
constructor(
private http: HttpClient,
private config: SancusConfiguration,
)
{
}
失败的测试:
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ AppModule ],
declarations: [ ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
我已在 NgModule 的提供程序中列出了 AuthenticationProvider:
@NgModule({
declarations: [
AppComponent,
LoginComponent,
....
],
imports: [
BrowserModule,
AppRoutingModule,
CollapseModule.forRoot(),
ReactiveFormsModule,
HttpClientModule
],
schemas: [ NO_ERRORS_SCHEMA ],
providers: [
AuthenticationProvider,
.....
],
bootstrap: [AppComponent]
})
export class AppModule { }
最佳答案
- 您必须在测试模块中列出您的提供程序,因为
AppModule
不会导出其提供程序。 - 您也不应该加载整个
AppModule
来仅测试LoginComponent
。 - 您必须模拟这些提供商,因为它们看起来像是在进行网络调用。
代码示例:
TestBed.configureTestingModule({
providers: [{provide: AuthenticationProvider, useValue: mockProvider}, ... ],
declarations: []
})
关于Angular 7 : NullInjectorError for failing test, 服务在组件中仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55160959/