Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 678
Marcio M. Avatar asked Jul 27 '17 19:07

Marcio M.


People also ask

How do you test a router for Event pipes?

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> .

How can you set up a router for testing Angular?

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.


1 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')      
});
like image 101
Felix Tsai Avatar answered Oct 21 '22 05:10

Felix Tsai