I am writing test case for angular 2 code using jasmine. I am trying to navigate back to the login page once the user logs out. How can I test the page location?
All you really need to do is test that the router navigate method is called with the correct argument (i.e. the route of the login page). Trying to test an actual navigation could cause more side effects than required for a unit test.
To check that the Router.navigate
method is called, simply use a 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']);
})
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