角度单元测试SwitchMap无法正常工作

时间:2018-04-19 00:20:44

标签: angular rxjs

我在服务中有以下方法:

login(username: string, password: string): Observable<any> {

  console.log('BEFORE switchMap');

  return this.webApiService.authenticate(username, password).pipe(switchMap((x) => {

    console.log('AFTER switchMap');

    return this.webApiService.getMe().pipe(switchMap((me) => {

      // ... Code removed for brevity ...

      this.isAuthenticatedField = true;

      return of(me);
    }));
  }));
}

注意:webApiService只是一个包装我们的Web服务API的角度服务。

正在使用以下测试(模拟Web服务)对此进行测试:

  it('should should set isAuthenticated on successful login', inject([AuthenticationService], (service: AuthenticationService) => {
    webApiSpy.authenticate.and.returnValue(of({}));
    webApiSpy.getMe.and.returnValue(of(me));
    service.login('testusername', 'secretpassword');
    expect(service.isAuthenticated).toEqual(true);
  }));

当我在浏览器中运行它时,一切正常。然而,当我在测试中运行它时,我将'BEFORE switchMap'行打印到控制台但我从未得到'AFTER switchMap'。

1 个答案:

答案 0 :(得分:0)

正如Harry Ninh亲切地指出的那样,我需要像这样订阅观察者:

  it('should should set isAuthenticated on successful login', inject([AuthenticationService], (service: AuthenticationService) => {
    webApiSpy.authenticate.and.returnValue(of({}));
    webApiSpy.getMe.and.returnValue(of(me));
    service.login('testusername', 'secretpassword').then(() => {
      expect(service.isAuthenticated).toEqual(true);
    });   
  }));
相关问题