How can I test `Router NavigationEnd Event` in angular 2?

Viewed 6652

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.

2 Answers

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')      
});
Related