Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error:NullInjectorError: No provider for Router

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

like image 603
canerandagio Avatar asked Oct 01 '20 08:10

canerandagio


1 Answers

Just import RouterTestingModule to your imports array in the TestBed

TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  providers:[
    GalleryComponent, 
    {provide:AuthenticationService}, 
    {provide:IterableDiffers}
  ]
})
like image 62
Owen Kelvin Avatar answered Oct 29 '22 01:10

Owen Kelvin