All you really need to do is verify that the router's navigation method is called with the correct argument (i.e., the path of the login page). Trying to test the actual navigation may cause more side effects than is required for the unit test.
To verify that the Router.navigate
method is Router.navigate
called, just use the stub and spy on it.
@Component({}) class SomeComponent { constructor(private router: Router) {} logout() { this.router.navigate(['/login']) } } let routerStub; beforeEach(() => { routerStub = { navigate: jasmine.createSpy('navigate'); } TestBed.configureTestModule({ declaration: [ SomeComponent ], providers: [ { provide: Router, useValue: routerStub } ] }); }); it('it should navigate to login after user logs out', () => { let component = TestBed.createComponent(SomeComponent).componentInstance; component.logout(); expect(routerStub.navigate).toHaveBeenCalledWith(['/login']); })
source share