error:NullInjectorError: No provider for Router

5.4k views Asked by At

I have to test one component and get this error NullInjectorError: R3InjectorError(DynamicTestModule)[AuthenticationService -> Router -> Router]: NullInjectorError: No provider for Router!**" The component I'm testing have two dependencies and I don't know hot to provide both them in the test with 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)
    })
...

how to provide both dependencies?
I read the Angular DOC and I didn't find the solution, I sew other asks on SO but without find solutions.
Thanks

2

There are 2 answers

0
Owen Kelvin On BEST ANSWER

Just import RouterTestingModule to your imports array in the TestBed

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

You just inject every dependency you have in the component's constructor:

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

If you need to use Angular router too:

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

And no need to add:

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

Afterwards, you can just call and work with the dependency you want.