我正在尝试对一个角度保护器进行单元测试,该角度保护器管道属于认证服务的可观察量。订阅发生在警卫canActivate()
方法中。
我在身份验证服务observable上使用jasmine间谍来返回值,但是我的单元测试中从未调用过间谍。
在测试组件时,我使用fixture.detectChanges()
,但对于这个后卫,我找不到一种方法来测试它根据可观察值返回正确的东西。
AUTH-guard.ts:
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(): Observable<boolean> {
return this.authService.isAuthenticated$.pipe(
map(e => {
if (e) {
return true;
}
}),
catchError((err) => {
this.router.navigate(['/login']);
return of(false);
})
);
}
}
auth.service.ts:
@Injectable()
export class AuthService {
private isAuthenticated = new BehaviorSubject<boolean>(false);
get isAuthenticated$(): Observable<boolean> { return this.isAuthenticated.asObservable(); }
...
}
AUTH-guard.spec.ts:
describe('Authuard', () => {
let authGuard: AuthGuard;
let authService: jasmine.SpyObj<AuthService>;
beforeEach(() => {
const authServiceSpy = jasmine.createSpyObj('AuthService', ['isAuthenticated$']);
TestBed.configureTestingModule({
providers: [
AuthGuard,
{ provide: AuthService, useValue: authServiceSpy }
]
});
authGuard = TestBed.get(AuthGuard);
authService = TestBed.get(AuthService);
});
it('should create', () => {
expect(authGuard).toBeDefined();
});
/* This test fails */
it('should return false when not authenticated', () => {
authService.isAuthenticated$.and.returnValue(of(false));
authGuard.canActivate().subscribe(canActivate => {
expect(canActivate).toBe(false);
});
});
});
第二次测试失败了this.authService.isAuthenticated$.pipe is not a function
。间谍在isAuthenticated $上返回的值不被采用。
当身份验证服务返回的可观察值发生变化时,如何测试保护返回正确的值?茉莉花间谍有可能吗?
尝试throwError
如下:
import { throwError } from 'rxjs';
it('should return false when not authenticated', () => {
spyOn(authService,'isAuthenticated$').and.returnValue(throwError('error'));
authGuard.canActivate().subscribe(canActivate => {
expect(canActivate).toBeFalsy();
});