[英]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.