Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
})
like image 679
karthik_personal Avatar asked Apr 20 '19 13:04

karthik_personal


People also ask

How do you test a router navigate in Angular components?

We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.

How do I navigate a router unit test?

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. 3) Finally, create routerSpy and create a jasmine spy to watch the navigate method.

How do I use this router navigate in Angular 8?

Accessing the route is a two step process. Include router-outlet tag in the root component template. Use routerLink and routerLinkActive property in the required place.


1 Answers

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']);
});
like image 172
Sourav Dutta Avatar answered Oct 10 '22 08:10

Sourav Dutta