how to unit test router.navigate in angular app [duplicate]
Asked Answered
S

1

18

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
})
Shanley answered 20/4, 2019 at 13:16 Comment(2)
Take a look at the Angular documentation concerning testing the router. angular.io/guide/testing#routing-component. The general strategy is to create a spy object with jasmine and use that spy object in the tests.Motheaten
The top answer was taken from: marclloyd.co.uk/javascript/…Mendicity
W
2

Some times, I put, dynamically, others arguments to call navigate. So, to expect only the path I uses into my test:

...
test('Navigate to /nextPage.', inject([Router], (mockRouter: Router) => {

  const spy = spyOn(mockRouter, 'navigate').and.stub();

  component.goToNextPageMethod();

  expect(spy.calls.first().args[0]).toContain('/nextPage');

}));
...

Reference: https://semaphoreci.com/community/tutorials/testing-routes-in-angular-2

Widow answered 21/5, 2020 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.