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
})
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.
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.
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.
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']);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With