16

I am running unit test for angular app, I want to unit test if navigation is working correctly in angular app.

 if (this.customer.length == 0) {
     this.router.navigate(['/nocustomer']);
 } 

And the unit test for this

 it(`should navigate to nocustomer`,()=>{
   component.customers.length=0;
   //what must be written here to check this
})
Gregor Albert
  • 819
  • 1
  • 11
  • 23
karthik_personal
  • 369
  • 1
  • 3
  • 14
  • Take a look at the Angular documentation concerning testing the router. https://angular.io/guide/testing#routing-component. The general strategy is to create a spy object with jasmine and use that spy object in the tests. – josavish Apr 20 '19 at 14:04
  • The top answer was taken from: https://marclloyd.co.uk/javascript/spying-on-router-navigate-in-angular-2-unit-tests/ – General Grievance Feb 01 '23 at 20:07

1 Answers1

1

Some times, I put, dynamically, others arguments to call navigate. So, to expect only the path I uses into my test:

...
test('Navigate to /nextPage.', inject([Router], (mockRouter: Router) => {

  const spy = spyOn(mockRouter, 'navigate').and.stub();

  component.goToNextPageMethod();

  expect(spy.calls.first().args[0]).toContain('/nextPage');

}));
...

Reference: https://semaphoreci.com/community/tutorials/testing-routes-in-angular-2

Akostha
  • 679
  • 7
  • 8