How to test Angular2's router.navigate?

前端 未结 4 1045
囚心锁ツ
囚心锁ツ 2021-01-31 07:58

I\'ve run into missing messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is

4条回答
  •  甜味超标
    2021-01-31 08:44

    If you want to test the router without mocking it you can just inject it into your test and then spy directly on the navigate method there. The .and.stub() will make it so the call doesn't do anything.

    describe('something that navigates', () => {
        it('should navigate', inject([Router], (router: Router) => {
          spyOn(router, 'navigate').and.stub();
          expect(authGuardService.canActivate({}, {})).toBe(false);
          expect(router.navigate).toHaveBeenCalledWith(['/login']);
        }));
      });
    

提交回复
热议问题