【问题标题】:Angular unit test SwitchMap not working角度单元测试 SwitchMap 不起作用
【发布时间】:2018-09-29 08:27:06
【问题描述】:

我在服务中有以下方法:

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 的 Angular 服务。

正在使用以下测试(模拟 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'。

【问题讨论】:

  • 可以尝试订阅登录方式吗?
  • 谢谢@HarryNinh,我现在觉得有点傻,溪流很冷,当然!有时你盯着事物年龄而忽略了显而易见的事情:)

标签: angular rxjs


【解决方案1】:

正如 Harry Ninh 所指出的,我需要像这样订阅 observable:

  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);
    });   
  }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2015-08-24
    • 2018-03-09
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多