[英]Invalid provider for the NgModule 'DynamicTestModule' when testing a service in Angular 2
[英]NullInjectorError: StaticInjectorError(DynamicTestModule) When Testing in Angular 2
我是 Angular2 的新手,并试图在app.component.spec.ts
文件中编写一个测试。 我的应用程序相对简单,除了它从 3rd 方库(由同事编写)导入 LoginComponent 和 LogoutComponent 之外。 这些组件现在分别用于路由登录或注销,非常简单。 运行ng serve
编译正常,应用程序“平稳”运行。 但是,运行ng test
给了我这个错误:
NullInjectorError: StaticInjectorError(DynamicTestModule)[LogoutComponent -> SessionService]:
StaticInjectorError(Platform: core)[LogoutComponent -> SessionService]:
NullInjectorError: No provider for SessionService!
LogoutComponent 是从不同的项目导入的。 此错误是否意味着我需要进入该项目并进行一些更改,还是应该在我的项目中以某种方式模拟 SessionService?
规格代码:
import {} from 'jasmine';
import {async, TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
import {AuthErrorStateService, LogoutComponent} from '@custom-library';
import {AppComponent} from './app.component';
import {AppErrorStateService} from './core/error-states/app-error-state.service';
import {TopNavComponent} from './core/top-nav/top-nav.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed
.configureTestingModule({
imports: [RouterTestingModule],
providers: [
AppErrorStateService, AuthErrorStateService
],
declarations: [AppComponent, TopNavComponent, LogoutComponent],
})
.compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'My App'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('My App');
});
it('should render title in a h1 tag', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toEqual('Welcome to My App!');
});
});
问题是像这样在TestBed
声明多个组件
declarations: [AppComponent, TopNavComponent, LogoutComponent]
当测试调用compileComponents()
时,会导致多个组件被实例化。 发生这种情况时, declarations
数组中的每个组件都需要在providers
数组中declarations
其依赖项才能完成实例化。 声明的组件之一取决于SessionService
,但该服务不存在于提供者中,因此您会得到NullInjectorError
。
对此有两种解决方案:
declarations
数组中声明一个组件并将schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
添加到TestBed
配置对象providers
数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.