Does anyone know how can I test Router NavigationEnd Event
? I have the code below in Angular 2 and I am using Jasmine.
import { Injectable, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, Event } from '@angular/router';
@Injectable()
export class IhmPageClassService {
emitPageClass = new EventEmitter<string>();
currentRoute: string;
constructor(router: Router) {
router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
this.currentRoute = (<NavigationEnd>event).url;
}
});
}
}
Thanks.
To test router events, we need to mock the router service object. In the test session configuration, we will replace events property of router as an Observable object. To have access to the events observable object, we create a separate variable of ReplaySubject<RouterEvent> .
We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.
So I've had some luck testing this using Subjects.
In your test setup you create a eventsSubject.
let eventsSub = new BehaviorSubject<any>(null);
Then create your routerStub:
routerStub = {
events: eventsSub
}
Then create the NavigationEnd object.
let homeNav = new NavigationEnd(1, 'home', 'home');
Using the routerStub now as the value for the Router
Service in your tests you should now be able to test your function.
it('should set the currentRoute correctly', () => {
eventSub.next(homeNav);
fixture.detectChanges();
expect(component.currentRoute).toEqual('home')
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With