如何解决错误:NullInjectorError:没有路由器的提供程序
我必须测试一个组件并得到此错误NullInjectorError:R3InjectorError(DynamicTestModule)[AuthenticationService-> Router-> Router]: NullInjectorError:路由器无提供程序!**” 我正在测试的组件有两个依赖关系,我不知道在测试中同时为它们提供测试平台是很热的 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 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);
然后,您可以调用并使用所需的依赖项。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。