how to unit test router.navigate in angular app

karthik_personal picture karthik_personal · Apr 20, 2019 · Viewed 10.9k times · Source

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

Answer

Sourav Dutta picture Sourav Dutta · Apr 20, 2019

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']);
});