0

私は今度は角2を書いていますが、私は最初のジャスミンテストを書いているだけで、少し難しかったです。私は、CanActivateサービスの実装方法CanActivateが動作していることをテストしようとしており、期待通りにtrueまたはfalseを返しています。ジャスミンテストでRouterStateSnapshotを黙って

私の方法は、次のようになります。私のテストの

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { 
    return this.store$ 
     .map((store: StoreState) => store.currentUser) 
     .first() 
     .map((user) => { 
      if (user.isAuthenticated) { 
       return true; 
      } 

      // TODO: This needs refactoring. Need to provide RouterStateSnapshot in test, 
      // rather than ignoring it! 
      this.redirectUrl = state ? state.url : ''; 
      this.injector.get(Router).navigate(['/login']); 
      return false; 
     }); 
} 

抽出物は、以下のようになります。私はservice.canActivateに/スタブ/私のコールの何でも二番目のパラメータを模擬するにはどうすればよい

service = TestBed.get(AuthGuardService); 

it('should prevent navigation',() => { 
    service.canActivate(null, null).subscribe((res) => expect(res).toBeTruthy()); 
}); 

、単純にヌルを渡すのではなく、

答えて

1
describe('AuthGuard',() => { 
    let mockSnapshot: RouterStateSnapshot; 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     imports: [ 
     // so we can get the Router injected 
     RouterTestingModule, 
     // other imports as needed 
     ], 
     // usual config here 
    }); 

    // create a jasmine spy object, of the required type 
    // toString is because we have to mock at least one method 
    mockSnapshot = createSpyObj<RouterStateSnapshot>('RouterStateSnapshot', ['toString']); 
    }); 

    it('should prevent non-authenticated access', 
    async(inject([AuthGuard, AuthService, Router], (guard: AuthGuard, auth: AuthService, router: Router) => { 
     // ensure we're logged out 
     auth.logout(); 

     // set the url on our mock snapshot 
     mockSnapshot.url = '/protected'; 

     // so we can spy on what's been called on the router object navigate method 
     spyOn(router, 'navigate'); 

     expect(guard.canActivate(null, mockSnapshot)).toBeFalsy(); 

     // check that our guard re-directed the user to another url 
     expect(router.navigate).toHaveBeenCalled(); 
    }))); 
    }); 
関連する問題