Rx.js React extension testing stream and intermediate results

183 views Asked by At

I have a module which stores data in this.store and takes keyboard events in this.stream

The relationship between this.store and this.stream is as follows

this.stream.subscribe(function(keyCode){
    this.store.add(100)
});

Now I am writing test cases against those events. I want to know when I click the keyboard 3 times respectively what will the intermediate results be.

So the test case is as follows:

var keyboardSource = Rx.Observable.create(function(observer) {
    observer.onNext({
      keyCode: defaultValidOption.default.keyboardData[0]
    });
    observer.onNext({
      keyCode: defaultValidOption.default.keyboardData[1]
    });
    observer.onNext({
      keyCode: defaultValidOption.default.keyboardData[2]
    });
  });

module.stream.subscribe(x => {
    module.store.total.should.equal(300);
    done();
});

This is correct because I can get the final result when the entire stream event is fired.

But the following is not correct.

module.stream.bufferWithCount(2).subscribe(x => {
    module.store.total.should.equal(200);
    done();
});

So how to I delay those events in my test case so that I can get imtermediate results. Thanks.

1

There are 1 answers

0
paulpdaniels On BEST ANSWER

When testing you should use the TestScheduler to explicitly control timings rather than relying on whatever the defaults are. So I would recommend you change your test code to:

var onNext = Rx.ReactiveTest.onNext;
var onCompleted = Rx.ReactiveTest.onCompleted;
var scheduler = new Rx.TestScheduler();

var keyboardSource =  scheduler.createHotObservable(
onNext(10, {keyCode: defaultValidOption.default.keyboardData[0]}),
onNext(20, {keyCode: defaultValidOption.default.keyboardData[1]}),
onNext(30, {keyCode: defaultValidOption.default.keyboardData[2]}),
onCompleted(100));

//Hook up keyboardSource to your stream
keyboardSource.subscribe(/*However your stream is hooked up*/);

//You can then move the scheduler's time forward at your own pace

scheduler.advanceBy(20);

module.store.total.should.equal(200);

scheduler.advanceBy(10);

module.store.total.should.equal(300);

done();