[英]spy on observable inside method
我想通过调用retrieveToken来验证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(,)
您可以在测试规范文件中定义服务模拟,如下所示:
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应该可用。
我希望这能帮到您 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.