angularunit-testingrouternavigateurl

how to unit test router.navigate in angular app


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
})

Solution

  • 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