Preparing code for testing

时间:2015-07-08 15:47:29

标签: javascript rxjs

If I have a function like this:

function batchByTime(obs) {
  return obs.bufferWithTime(300).take(10);
}

and I want to test it like this:

var onNext = Rx.ReactiveTest.onNext,
  onCompleted = Rx.ReactiveTest.onCompleted,
  subscribe = Rx.ReactiveTest.subscribe;

QUnit.test("hello test", function(assert) {
  var scheduler = new Rx.TestScheduler();
  var samplesObservable = scheduler.createHotObservable(
    onNext(100, 1),
    onNext(200, 2),
    onNext(450, 3),
    onNext(1000, 4),
    onCompleted(1100)
  );

  var results = scheduler.
    startWithTiming(function() {
    return batchByTime(samplesObservable);
  }, 0, 0, 1200);

  var msgs = results.messages;
  assert.equal(msgs[0].toString(), onNext(300, [1, 2]).toString());
  assert.equal(msgs[0].toString(), onNext(600, [3]).toString());
  assert.equal(msgs[0].toString(), onNext(900, [4]).toString());
});

I'd expect that to work, but instead I get all the notifications at once, receiving:

Expected:   
"OnNext(1,2)@300"

Result:
"OnNext(1,2,3,4)@1100"

for each assertion.

I understand that this would work if I pass the TestScheduler scheduler to batchByTime, and use this scheduler as a parameter in the bufferWithTime operator. But doesn't that defeat the whole purpose of testing? Ideally I wouldn't have to modify the original code to test it.

1 个答案:

答案 0 :(得分:0)

正如原始问题的评论者指出的那样,如果没有提供调度程序,则应使用bufferWithTime中的默认调度程序,通过使用可能的调度程序对代码进行参数化来使代码更易于测试。