错误:NullInjectorError:没有提供程序Router

5

我需要测试一个组件,但是得到了这个错误信息:NullInjectorError: R3InjectorError(DynamicTestModule)[AuthenticationService -> Router -> Router]: NullInjectorError: No provider for Router!**" 我正在测试的组件有两个依赖项,但我不知道如何在测试时使用testbed提供这两个依赖项。 gallery.component.ts

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

gallery.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文档,但没有找到解决方案,我还在SO上看到其他问题,但没有找到解决方案。
谢谢


谢谢回复,但我不想测试路由。gallery.component不是一个路由,它是container.component的子组件。 - canerandagio
好的,完成了!现在我又遇到了一个错误:“[AuthenticationService -> AuxiliarService -> Store -> Store]:NullInjectorError:没有为Store提供程序!” - canerandagio
我提供了 "{provide:AuthenticationService, useValue:authServiceMock}",完成了,谢谢。 - canerandagio
2个回答

8

在TestBed的import数组中导入RouterTestingModule即可。

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

0

你只需要在组件的构造函数中注入所有依赖项:

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

如果您也需要使用Angular路由器:
constructor( private authService:AuthenticationService, private iterableDiffers: IterableDiffers, private router: Router){}

不需要添加:

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

之后,您只需调用并使用所需的依赖项即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接