窥探可观察的内部方法

问题描述 投票:0回答:1

我想验证this.isLoggedIn是通过调用retrieveToken来设置的。

我也想监视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(,)

angular unit-testing jasmine angular2-observables
1个回答
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应该可用。

我希望这能帮到您 :)

© www.soinside.com 2019 - 2024. All rights reserved.