Angular 7 Test: NullInjectorError: No provider for ActivatedRoute
Asked Answered
A

6

102

Hi have some error with testing my App made with Angular 7. I do not have much experience in angular, so I would need your help+

Error: StaticInjectorError(DynamicTestModule)[BeerDetailsComponent -> ActivatedRoute]: 
  StaticInjectorError(Platform: core)[BeerDetailsComponent -> ActivatedRoute]: 
    NullInjectorError: No provider for ActivatedRoute!

the testing code is like this:

import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { BeerDetailsComponent } from './beer-details.component';
import {
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';

describe('BeerDetailsComponent', () => {
  let component: BeerDetailsComponent;
  let fixture: ComponentFixture<BeerDetailsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [ BeerDetailsComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BeerDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create',
  inject(
    [HttpTestingController],
    () => {
      expect(component).toBeTruthy();
    }
  )
)
});

I really can't find any solution.

Daniele

Alver answered 6/12, 2018 at 15:10 Comment(0)
P
73

Add the following import

  imports: [ 
    RouterModule.forRoot([]),
    ...
  ],
Pasadis answered 6/12, 2018 at 15:12 Comment(7)
where should i import RouterModule.forRoot([]),?Alver
In the module import { RouterModule } from '@angular/router';Pasadis
RouterModule should not be included in the test filesImmortalize
thats not a proper solution, by this you need to define all roter module provider params, APP_BASE_HREF token etc. Use instead RouterTestingModule with no router provider declarationsTil
Would be a good answer if you stated where the import should be addedFitzsimmons
@daniele-caputo, make sure that you have accepted the currect answer. other answers with import: [RouterTestingModule] resolved my error.Atomy
The correct answer is provided by @prathvi-shetty below.Diligence
O
148

You have to import RouterTestingModule

import { RouterTestingModule } from "@angular/router/testing";

imports: [
    ...
    RouterTestingModule
    ...
]
Ostentation answered 23/10, 2019 at 9:8 Comment(9)
When I do this, I start getting the error NullInjectorError: No provider for ActivatedRoute!Frit
Did you imported this module into the spec file?Ostentation
I believe the solution was to add a provider for the route, using an anonymous object containing the properties accessed by the test.Frit
This should be the accepted answerDisconnect
If you are coming to this in 2022 then RouterTestingModule now lives in @angular/common/http/testingNorinenorita
@MikePoole I just used the RouterTestingModule in Angular 17, and it still lives on @angular/router/testing and not @angular/common/http/testingLoge
@Loge It does still exist there, but it is marked as deprecated.Ordway
@Ordway Doesn't deprecation means it will be dropped in a matter of time, and could possibly cause compilation error?Loge
RouterTestingModule is deprecated. Use provideRouter or RouterModule.forRoot instead.Biak
P
73

Add the following import

  imports: [ 
    RouterModule.forRoot([]),
    ...
  ],
Pasadis answered 6/12, 2018 at 15:12 Comment(7)
where should i import RouterModule.forRoot([]),?Alver
In the module import { RouterModule } from '@angular/router';Pasadis
RouterModule should not be included in the test filesImmortalize
thats not a proper solution, by this you need to define all roter module provider params, APP_BASE_HREF token etc. Use instead RouterTestingModule with no router provider declarationsTil
Would be a good answer if you stated where the import should be addedFitzsimmons
@daniele-caputo, make sure that you have accepted the currect answer. other answers with import: [RouterTestingModule] resolved my error.Atomy
The correct answer is provided by @prathvi-shetty below.Diligence
S
31

I had this error for some time as well while testing, and none of these answers really helped me. What fixed it for me was importing both the RouterTestingModule and the HttpClientTestingModule.

So essentially it would look like this in your whatever.component.spec.ts file.

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProductComponent],
      imports: [RouterTestingModule, HttpClientTestingModule],
    }).compileComponents();
  }));

You can get the imports from

import { RouterTestingModule } from "@angular/router/testing";
import { HttpClientTestingModule } from "@angular/common/http/testing";

I dont know if this is the best solution, but this worked for me.

Sympathizer answered 11/7, 2020 at 10:44 Comment(0)
M
24

This issue can be fixed as follows:

  1. In your corresponding spec.ts file import RouterTestingModule

    import { RouterTestingModule } from '@angular/router/testing';

  2. In the same file add RouterTestingModule as one of the imports

     beforeEach(() => {
        TestBed.configureTestingModule({
        imports: [RouterTestingModule],
        providers: [Service]
      });
     });
    
Musca answered 29/9, 2020 at 9:41 Comment(0)
D
8

Example of a simple test using the service and ActivatedRoute! Good luck!

    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { HttpClientModule } from '@angular/common/http';
    import { MyComponent } from './my.component';
    import { ActivatedRoute } from '@angular/router';
    import { MyService } from '../../core/services/my.service';


    describe('MyComponent class test', () => {
    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;
    let teste: MyComponent;
    let route: ActivatedRoute;
    let myService: MyService;

    beforeEach(async(() => {
        teste = new MyComponent(route, myService);
        TestBed.configureTestingModule({
        declarations: [ MyComponent ],
        imports: [
            RouterTestingModule,
            HttpClientModule
        ],
        providers: [MyService]
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('Checks if the class was created', () => {
        expect(component).toBeTruthy();
    });

    });
Duntson answered 6/1, 2020 at 19:52 Comment(2)
Are you using teste anywhere? for what is it needed?Underglaze
I use everywhere I work, a way to ensure that the application keeps working after some change without breaking my code.Duntson
B
1

RouterTestingModule is deprecated. Use providerRouter or RouterModule.forRoot instead. The accepted answer uses RouterModule.forRoot. If you want to use providerRouter instead, add providers: [provideRouter([])] below imports

import { provideRouter } from '@angular/router';

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [ AppComponent ],
      providers: [provideRouter([])],
    }).compileComponents();
  }
Biak answered 22/3, 2024 at 22:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.