Search code examples
angularunit-testingjasmineangular-providers

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


Solution

  • Just import RouterTestingModule to your imports array in the TestBed

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