【问题标题】:Angular2 testing logic before .subscribe.subscribe 之前的 Angular2 测试逻辑
【发布时间】:2016-05-21 14:49:22
【问题描述】:

我目前正在为我的一个组件编写单元测试。特别是,我有login(): void 功能。这是简化的逻辑:

login(): void {
  this.showSpinner = true;
  this.userService.login(loginData)
    .subscribe(result => {
      this.showSpinner = false;
    }
  )
}

我正在努力编写一个测试,在调用 userService.login 之前检查 showSpinner 属性是否设置为 true

这是我的测试:

it('should display the spinner when the form is being saved',
  inject([TestComponentBuilder], fakeAsync((tcb: any) => {
    createComponent(tcb).then((fixture:ComponentFixture<any>) => {
      fixture.componentInstance.login();
      expect(fixture.componentInstance.showSpinner).toBe(true);
      tick();
    });
  })));
});

这个测试失败了,因为.subscribe 被立即解决/运行(我尝试在我的组件中注释掉this.showSpinner = false,并且测试通过了)。

在我的 userService 模拟中,对于 login 方法模拟,我有以下内容:

this.loginSpy = this.spy('login').andReturn(Observable.of(this));

thismockUserService

我确信我正在正确地模拟 userService,特别是 userService 上的 login 方法,因为我对该组件进行了其他测试,这些测试运行正常。

我还尝试从我的间谍返回Observable.of(this).delay(1),然后在我的测试中调用tick(1)。然而,这会导致不一致的行为,因为有时我的测试通过了,但有时我收到一条错误消息:

Error: 1 periodic timer(s) still in the queue.

如何测试.subscribe() 之前的逻辑?

【问题讨论】:

    标签: unit-testing angular rxjs observable angular2-testing


    【解决方案1】:

    经过更多考虑,我意识到我当前的代码不遵守单一职责原则。这个想法来自于这样一个事实,每个人都在重复你应该“重构难以测试的代码”。

    考虑到这一点,我已将在调用userService.login 之前需要完成的所有逻辑转移到它自己的单独函数中。这基本上导致:

    login():void {
      this.userService.login(this.loginData)
        .subscribe(result => {
           this.showSpinner = false;
        });
    }
    
    formSubmit(): void {
      this.showSpinner = true;
      this.login();
    }
    

    这个逻辑现在更容易测试了。

    但是当我们测试formSubmit() 时,我们需要记住在我们的login() 方法上添加一个间谍,就像我们不这样做一样,formSubmit() 只会调用@ 987654326@,它将再次同步完成,我们将遇到同样的问题。所以我对这个功能的新的和最终的测试是:

    it('should display the spinner when the form is being saved',
      inject([TestComponentBuilder], fakeAsync((tcb: any) => {
        createComponent(tcb).then((fixture:ComponentFixture<any>) => {
          var loginSpy = spyOn(fixture.componentInstance, 'login');
          fixture.componentInstance.formSubmit();
          expect(fixture.componentInstance.showSpinner).toBe(true);
        });
      })));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多