Looking to simulate router.events
in a unit test, as suggested by the title.
Within my component, I am using regex to extract the first occurrence of text between slashes in the URL; for example, /pdp/
constructor(
private route: ActivatedRoute,
private router: Router,
}
this.router.events.pipe(takeUntil(this.ngUnsubscribe$))
.subscribe(route => {
if (route instanceof NavigationEnd) {
// debugger
this.projectType = route.url.match(/[a-z-]+/)[0];
}
});
Encountering errors in my unit tests during component setup: Cannot read property '0' of null
. When I analyze with the debugger enabled, the value of route
does not appear to be properly set, although I have defined it in the unit test itself. Various approaches have been attempted based on resources like this post: Mocking router.events.subscribe() Angular2 and others.
Initial approach:
providers: [
{
provide: Router,
useValue: {
events: of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit'))
}
},
// Mocking ActivatedRoute as well
{
provide: ActivatedRoute,
useValue: {
snapshot: { url: [{ path: 'new' }, { path: 'edit' }] },
parent: {
parent: {
snapshot: {
url: [
{ path: 'pdp' }
]
}
}
}
}
}
]
Second attempt (following the aforementioned post):
class MockRouter {
public events = of(new NavigationEnd(0, '/pdp/project-details/4/edit', '/pdp/project-details/4/edit'))
}
providers: [
{
provide: Router,
useClass: MockRouter
}
]
Third attempt (also inspired by the above post):
class MockRouter {
public ne = new NavigationEnd(0, '/pdp/project-details/4/edit', '/pdp/project-details/4/edit');
public events = new Observable(observer => {
observer.next(this.ne);
observer.complete();
});
}
providers: [
{
provide: Router,
useClass: MockRouter
}
]
Fourth attempt:
beforeEach(() => {
spyOn((<any>component).router, 'events').and.returnValue(of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit')))
...
Fifth attempt:
beforeEach(() => {
spyOn(TestBed.get(Router), 'events').and.returnValue(of({ url:'/pdp/project-details/4/edit' }))
...
In all the instances mentioned above, the variable route
remains unset; the NavigationEnd
object is displayed as:
{ id: 1, url: "/", urlAfterRedirects: "/" }
Any insights or suggestions?