簡體   English   中英

NullInjectorError: StaticInjectorError(DynamicTestModule) 在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM