无法测试canActivate()的错误路径-Angular2 +

时间:2018-08-06 14:24:51

标签: javascript angular typescript

有人可以帮助我测试可确定应用程序AuthGuard的canActivate函数的错误路径吗?

看来我在伪造RouterStateSnapshot ...上遇到了麻烦...

后卫

canActivate(
      next: ActivatedRouteSnapshot,
      state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    console.log(next);
    console.log(state);
    console.log(localStorage.getItem('token'));

2 个答案:

答案 0 :(得分:2)

满足所有条件以通过虚假测试:

it('should return false', () => {
  spyOn(guard['authService'], 'getStoredToken').and.returnValue('');

  expect(guard.canActivate(null, { url: 'foo' } as any)).toEqual(false);
});

答案 1 :(得分:0)

我找到了解决方法...

const next: ActivatedRouteSnapshot;
const state: any = {url: ''};
const queryParams = {queryParams: {returnUrl: ''}};

it('should return false and not navigate', () => {
    // Set token as '' as this is what would be returned by 'getToken' function
    localStorage.setItem('token', '');
    expect(guard.canActivate(next, state)).toEqual(false);
    expect(navSpy).toHaveBeenCalledWith(['login'], queryParams);
  });