Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking router.events.subscribe() Angular2

In my app.component.ts I have the following ngOnInit function:

ngOnInit() {     this.sub = this.router.events.subscribe(e => {       if (e instanceof NavigationEnd) {         if (!e.url.includes('login')) {           this.loggedIn = true;         } else {           this.loggedIn = false;         }       }     });   } 

Currently I'm testing if the sub is not null but I want to test the function with a 100% coverage.

I want to mock the router object so that I can simulate the URL and then test if the this.loggedIn is correctly set.

How would I proceed to mock this function? I tried it but I don't know how I would take this on with the callback involved and with the NavigationEnd.

like image 852
stijn.aerts Avatar asked Jul 20 '16 07:07

stijn.aerts


1 Answers

I have found the answer, if someone is looking for it:

import { NavigationEnd } from '@angular/router'; import { Observable } from 'rxjs/Observable';  class MockRouter {   public ne = new NavigationEnd(0, 'http://localhost:4200/login', 'http://localhost:4200/login');   public events = new Observable(observer => {     observer.next(this.ne);     observer.complete();   }); }  class MockRouterNoLogin {   public ne = new NavigationEnd(0, 'http://localhost:4200/dashboard', 'http://localhost:4200/dashboard');   public events = new Observable(observer => {     observer.next(this.ne);     observer.complete();   }); } 
like image 99
stijn.aerts Avatar answered Oct 06 '22 02:10

stijn.aerts