我对 RxJS 还算陌生,对使用 Jest 进行单元测试也很陌生,在尝试测试一些模拟的 RxJS 可观察值时,我遇到了一个非常令人困惑的问题。
为了模拟数据流,我在测试 spec.js
文件中创建了一个 Observable,如下所示:
var Rx = require("rx");
var source = Rx.Observable.interval(500).take(10);
source.subscribe(
function(x){ console.log(x) },
function(e){ console.log(e) },
function(){ console.log('completed') }
);
虽然在作为 Node 脚本运行时它可以正确记录,但在通过 npm test
运行时它不会记录任何内容。 Observable.delay
和 setTimeout
函数似乎不起作用。
最佳答案
这对我有用:
var Rx = require("rx");
describe("Interval Test", () => {
const source = Rx.Observable.interval(100);
let count = 0;
source.subscribe(
x => count++,
e => console.log("error: ", e),
() => console.log("complete"));
it("run for 1 second", done => {
setTimeout(() => {
console.log('one second passed');
expect(count).toBe(10);
done();
}, 1010)
});
});
看来我需要在我的 it
测试函数中设置一个超时,以便这个异步可观察量能够执行。同样重要的是 done()
调用,以防止时间无限期地运行。
注意:或者,如果您想使用 Jest 的假时间来手动控制计时,这似乎也可行。我发现我不需要使用 VirtualTimeScheduler。
jest.useFakeTimers();
var Rx = require("rx");
var source = Rx.Observable.interval(500).take(10);
source.subscribe(
function(x){ console.log(x) },
function(e){ console.log(e) },
function(){ console.log('completed') }
);
jest.runAllTimers();
关于javascript - 如何在 Jest 中测试基于计时器的 RxJS 可观察量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48428059/