有人可以帮助我测试可确定应用程序AuthGuard的canActivate函数的错误路径吗?
看来我在伪造RouterStateSnapshot
...上遇到了麻烦...
后卫
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
console.log(next);
console.log(state);
console.log(localStorage.getItem('token'));
答案 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);
});