【问题标题】:Angular[karma] Async testing on ObservableObservable 上的 Angular[karma] 异步测试
【发布时间】:2019-03-18 09:24:22
【问题描述】:

我尝试测试一个异步案例。 我的组件:

  ngOnInit(private service: MyService) {
    this.isLoading = true;
    this.service.getData().subscribe((data) => {
      this.data = data;
      this.isLoading = false;
    });
  }

如您所见,我将 loading 设置为 true,当检查数据时,isLoading 变为 false。 这就是我要测试的。 我试过用滴答(),当稳定... 我监视 MyService 以返回带有 mockData 的 Observable,但我无法将 isLoading 捕获为 true。

感谢您的帮助。

【问题讨论】:

    标签: angular typescript rxjs karma-jasmine


    【解决方案1】:
    it('should ...', done => {
      const dataMock = {};
      spyOn(component['service'], 'getData').and.returnValue(of(dataMock);
      component['service'].getData().pipe(delay(500)).subscribe(data => {
        expect(component.data).toBe(dataMock));
        expect(component.isLoading).toBeFalsy();
        done();
      });
    
      expect(component.isLoading).toBeTruthy();
    });
    

    【讨论】:

    • 我没有问题将isLoading测试为false或component.data。我想测试的是 isLoading 为 true,(在服务订阅之前)
    • 谢谢,工作得很好,我尝试了超时而不是延迟,但没有工作。
    • 超时定义为Error if no value is emitted before specified duration。延迟是你想要的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多