If you are getting the following error while running ng test:
NullInjectorError: R3InjectorError(DynamicTestModule)[Router -> Router]:
NullInjectorError: No provider for Router! NullInjectorError: R3InjectorError(DynamicTestModule)[Router -> Router]:
NullInjectorError: No provider for Router!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'Router', 'Router' ] })
NullInjectorError: R3InjectorError(DynamicTestModule)[Router -> Router]:
NullInjectorError: No provider for Router!
at NullInjector.get (node_modules/@angular/core/fesm2020/core.mjs:9091:27)
at R3Injector.get (node_modules/@angular/core/fesm2020/core.mjs:9258:33)
at R3Injector.get (node_modules/@angular/core/fesm2020/core.mjs:9258:33)
at NgModuleRef.get (node_modules/@angular/core/fesm2020/core.mjs:22413:33)
at ChainedInjector.get (node_modules/@angular/core/fesm2020/core.mjs:22217:36)
at lookupTokenUsingModuleInjector (node_modules/@angular/core/fesm2020/core.mjs:3379:39)
at getOrCreateInjectable (node_modules/@angular/core/fesm2020/core.mjs:3424:12)
at ɵɵdirectiveInject (node_modules/@angular/core/fesm2020/core.mjs:10407:12)
at NodeInjectorFactory.factory (ng:///HeaderNavigationComponent/ɵfac.js:6:7)
at getNodeInjectable (node_modules/@angular/core/fesm2020/core.mjs:3609:44)
The solution is to import RouterTestingModule in your spec file of your component
beforeEach(async () => {
await TestBed.configureTestingModule({
imports:[RouterTestingModule]
}).compileComponents();
The complete file will look like this:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { YourComponent } from './YourComponent.component';
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture<YourComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports:[RouterTestingModule],
declarations:[....YourDeclarationsIfNeeded]
}).compileComponents();
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});