I have a component which uses Routes
. I want to unit test the routes but am unale to do so using RouterTestingModule
.
The spec
I have written is
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
....
fdescribe('HomepageContentComponentComponent', () => {
let component: HomepageContentComponentComponent;
let fixture: ComponentFixture<HomepageContentComponentComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports:[
RouterTestingModule.withRoutes([
{
path: 'new-practice-question',
component: NewPracticeQuestionComponent
}]),
ReactiveFormsModule,
HttpClientTestingModule
],
declarations: [ ...
],
providers:[
{provide: Location, useClass: SpyLocation},
{provide: LocationStrategy, useClass: MockLocationStrategy},
{provide: NgModuleFactoryLoader, useClass: SpyNgModuleFactoryLoader}
]
})
.compileComponents();
fixture = TestBed.createComponent(HomepageContentComponentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should navigate to New Questions Component when New Question button is clicked',fakeAsync(()=>{
let router:Router = TestBed.get(Router);
let location:Location = TestBed.get(Location);
console.log('initial router is ',router);
console.log('initial location is ',location);
//router.initialNavigation();
router.navigate(['new-practice-question']).then(()=>{
console.log('new router is ',router);
console.log('new location is ',location);
expect(location.path()).toBe('/new-practice-question');
});
}));
});
I am facing two issues
1) path()
doesn't seem to be defined in Location
but most of the examples I have seen online use path()
. So the comparison in expect
is failing.
2) I had to explicitly provide providers
for SpyLocation
etc. Why? Most of the example I have seen online seem to just use RouterTestingModule.withRoots
without need to explicitly provide providers
. If I don't do so, I get error no providers for Location!