how to unit test router.navigate in angular app

24,183

Check unit testing router in Angular

Do the following

1) Import the Router from @angular.

import { Router } from '@angular/router';

2) Add the Router to your providers array and swap it out for a routerSpy.

TestBed.configureTestingModule({
  providers: [
    { provide: Router, useValue: routerSpy }
  ]
})

3) Finally, create routerSpy and create a jasmine spy to watch the navigate method.

let routerSpy = {navigate: jasmine.createSpy('navigate')};

This will stop your unit test failing when the component can’t find the <router-outlet></router-outlet> element when the test runs.

You can then test that router.navigate() has been called using:

expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);

Hence, modify your it() statement like below and add the above config

it(`should navigate to nocustomer`, () => {
   component.customers = [];
   expect (routerSpy.navigate).toHaveBeenCalledWith(['/nocustomer']);
});
Share:
24,183
karthik_personal
Author by

karthik_personal

Updated on August 06, 2020

Comments

  • karthik_personal
    karthik_personal over 3 years

    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
    })
    
  • supertonsky
    supertonsky over 2 years
    The OP is asking for how to simulate navigation and not making assertions about navigation.
  • Sourav Dutta
    Sourav Dutta over 2 years
    While unit testing in angular, we don't check if Angular's router navigation is correct or not, we rather check our implementation, hence we test the code we wrote is doing what we intend it to.
  • supertonsky
    supertonsky over 2 years
    But what you're doing is actually checking if it navigated correctly with your call to toHaveBeenCalledWith. The OP is asking how to navigate and make assertions on the behavior of the subject under test. The OP is not asking if the navigation has been called.
  • Sourav Dutta
    Sourav Dutta over 2 years
    Where is OP asking how to navigate ? The OP requests , I want to unit test if navigation is working correctly and also it block states 'should navigate to nocustomer' , therefore the usage of toHaveBeenCalledWith checks if it was called with proper url, if the test passes that implies navigation was successful, it navigates to nocustomer, if you have a different solution or different expectations based on your understanding, please put it as a suggestion, comment or an answer.