我想通过调用restoreToken来验证是否设置了this.isLoggedIn。
我还想监视this.authService.currentToken
,这是否可能,或者还有另一种方法来验证可观察对象是否已订阅?
组件
public retrieveToken(): void {
this.authService.currentToken
.subscribe(status => {
if (status) {
this.isLoggedIn = true;
}
});
}
服务
export class AuthenticationService {
public currentTokenSubject: BehaviorSubject<any>;
public currentToken: Observable<any>;
constructor(private http: HttpClient) {
this.currentTokenSubject = new BehaviorSubject<any> ());
this.currentToken = this.currentTokenSubject.asObservable();
}
}
规格
it('', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
const tokenSpy = spyOn(authService, 'currenToken').and.returnValue(of({}));
app.retrieveToken();
expect(tokenSpy).toHaveBeenCalled();
});
错误消息
错误:: currenToken()方法不存在 用法:spyOn(,)
答案 0 :(得分:0)
您可以在测试规范文件中定义服务模拟,如下所示:
class AuthenticationServiceMock extends AuthenticationService {
// here you can define what you need, in your case it is currentToken
// which you need
}
然后在要设置提供程序的TestBed中,需要指定要使用创建的模拟类
providers: [
{
provide: AuthenticationService,
useValue: new AuthenticationServiceMock()
},
]
当您调用“ app.retrieveToken();”时,现在在测试用例中 currentToken应该可用。
我希望这会对您有所帮助:)