error:NullInjectorError:没有路由器的提供程序



我必须测试一个组件并得到此错误NullInjectorError:R3InjectorError(DynamicTestModule([AuthenticationService->Router->路由器]:NullInjectorError:没有路由器的提供程序**"我正在测试的组件有两个依赖项,我不知道如何在测试台的测试中同时提供它们图库组件.ts

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

图库组件规范

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导入TestBed 中的导入数组

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);

之后,您可以直接调用并使用您想要的依赖关系。

相关内容

  • 没有找到相关文章

最新更新