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