I am using RxJs to count how many packets arrive in a particular time window. My code basically looks like this:
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);
}
How to unit test this code using Rx TestScheduler? I could not find any suitable example for testing Subjects.
Have a look this example :
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With