Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine Test Case for Angular 2- Navigating to other page

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?

like image 833
devtiwa Avatar asked Dec 01 '16 00:12

devtiwa


1 Answers

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']);
})
like image 125
Paul Samsotha Avatar answered Oct 05 '22 03:10

Paul Samsotha