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.
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(); }); }
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