javascript – 在RxJs中使用TestScheduler测试主题

我正在使用RxJ来计算在特定时间窗口内到达的数据包数量.我的代码基本上是这样的:

var packetSubject = new Rx.Subject();
var packetsInWindow = [];

function startMonitoring() {
    var subscription = packetSubject
        .windowWithTime(1000)
        .select(function(window) {
            window.toArray().subscribe(function(elements) {
                packetsInWindow.push(elements.length);
            });
        })
        .subscribe();
}

function newPacket(packet) {
    packetSubject.onNext(packet);
}

如何使用Rx TestScheduler对此代码进行单元测试?我找不到任何合适的测试主题的例子.

解决方法:

看看这个例子:

   var x = 0,
       scheduler = new Rx.TestScheduler();

   var subject = new Rx.Subject();
   subject.throttle(100, scheduler).subscribe(function (value) {
       x = value;
   });

   scheduler.scheduleWithAbsolute(0, function () {
       subject.onNext(1);//trigger first event with value 1
   });
   scheduler.scheduleWithAbsolute(50, function () {
       expect(x).toEqual(0);//value hasn't been updated
   });
   scheduler.scheduleWithAbsolute(200, function () {
       expect(x).toEqual(1);//value update after throttle's windowDuration 
   });

   scheduler.start();

https://emmkong.wordpress.com/2015/03/18/how-to-unit-test-rxjs-throttle-with-rx-testscheduler/

上一篇:javascript – 使用运算符扩展RxJS Observable类


下一篇:javascript – RxJS:将历史数据与更新流相结合