簡體   English   中英

錯誤:NullInjectorError:沒有路由器提供程序

[英]error:NullInjectorError: No provider for Router

我必須測試一個組件並收到此錯誤 NullInjectorError: R3InjectorError(DynamicTestModule)[AuthenticationService -> Router -> Router]: NullInjectorError: No provider for Router!**" 我正在測試的組件有兩個依賴項,但我沒有知道 hot 在測試中使用 testbed gallery.component.ts提供它們

constructor( private authService:AuthenticationService, private iterableDiffers: IterableDiffers){
        this.iterableDiffer = iterableDiffers.find([]).create(null);
    }

畫廊.component.spec.ts

describe('GalleryComponent', () => {

    let component: GalleryComponent;
    let fixture: ComponentFixture<GalleryComponent>
    let authServiceMock: AuthenticationService
    let iterableDifferMock: IterableDiffers

    beforeEach(() => {
        TestBed.configureTestingModule({
        providers:[GalleryComponent, {provide:AuthenticationService}, {provide:IterableDiffers}]
    })
        

        fixture = TestBed.createComponent(GalleryComponent);
        component = fixture.componentInstance;

        authServiceMock = TestBed.inject(AuthenticationService)
    })
...

如何提供這兩個依賴項?
我閱讀了 Angular DOC,但沒有找到解決方案,我在 SO 上提出了其他問題,但沒有找到解決方案。
謝謝

只需將RouterTestingModule導入RouterTestingModule中的導入數組

TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  providers:[
    GalleryComponent, 
    {provide:AuthenticationService}, 
    {provide:IterableDiffers}
  ]
})

您只需注入組件構造函數中的所有依賴項:

constructor( private authService:AuthenticationService, private iterableDiffers: IterableDiffers){}

如果您也需要使用 Angular 路由器:

constructor( private authService:AuthenticationService, private iterableDiffers: IterableDiffers, private router: Router){}

並且無需添加:

this.iterableDiffer = iterableDiffers.find([]).create(null);

之后,您可以調用並使用您想要的依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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