首页 > 解决方案 > 发出值后 RxJS BehaviorSubject getValue 不一致(在 Jest 中测试时)

问题描述

我不明白为什么.getValue()返回 Observable 的默认值而不是发出的最后一个值。在测试 Observable 时,它​​会正确返回发出的值。

class TestA {
  readonly aSource: BehaviorSubject<number> = new BehaviorSubject(null);

  getA(): number {
    return this.aSource.getValue();
  }

  promise(): void {
    Promise.reject()
      .catch(() => {
        this.aSource.next(2);

        console.log(this.getA()); // Outputs: 2
      });
  }
}

describe('TestA', () => {
  it('promise', () => {
    const a = new TestA();
    a.promise();

    // Test 1 OK
    expect(a.aSource.asObservable()).toBeObservable(hot('a', {a: 2}));

    // Test 2 FAIL (returns null)
    expect(a.aSource.getValue()).toEqual(2);

    // Test 3 FAIL (returns null)
    expect(a.getA()).toEqual(2);
  });
});

澄清一下,该getValue()方法在测试之外运行良好,它仅在使用 Jest 测试时失败。

谢谢!

标签: typescriptrxjsjestjsrxjs-marbles

解决方案


原因是回调函数的异步性质catch。所以我认为如果你将你的期望语句包装在 中 setTimeout,并以异步方式运行测试,它就会变成绿色。


推荐阅读