typescript - 发出值后 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 测试时失败。
谢谢!
解决方案
原因是回调函数的异步性质catch
。所以我认为如果你将你的期望语句包装在 中 setTimeout
,并以异步方式运行测试,它就会变成绿色。
推荐阅读
- ios - CoreData 未显示查询条件
- python - 使用深度优先搜索在 python 中遍历二维列表
- racket - 如何将列表的第一个元素应用于列表的其余部分?
- apache-spark - 使用 Group By 结束 Spark 窗口的问题
- python - 如何在 Python3 中生成堆积条形图?
- css - 带有 id 的表在 css 上不显示 td 和 tr 周围的边框
- python-3.x - 平均数据框中的重复值
- php - 在保持 div 打开的同时更改整个页面
- javascript - 如何在 json 模型导出中保留自定义层名称并避免“TensorFlowOpLayer”
- swift - 简单的获取请求不适用于 AlamoFire