Menu

Angular Unit testing – Router navigate

When it comes to unit testing you will have to isolate your component and test that component without thinking about any of the dependencies, this is where you will have to use Mocks, it can be a Mocked service, Router, etc.

If you require to unit test a “router.navigate” you can spyOn Router like below.

describe('when user logged in', () => {

    it('should not navigate to singin page', inject([UserGuard, Router], (userGuard: UserGuard, router: Router) => {
      spyOn(router, 'navigate').and.stub();

      const canActivate = userGuard.canActivate();

      expect(canActivate).toBeTruthy();
      expect(router.navigate).not.toHaveBeenCalledWith(['/signin']);
    }));

  });

 

 

Leave a comment