Closed smwhit closed 9 years ago
Here is an example of how you might do this:
var onNext = Rx.ReactiveTest.onNext,
onCompleted = Rx.ReactiveTest.onCompleted;
//Use this to mock the input from your search bar
var testObservable = test_scheduler.createHotObservable(
onNext(350, {newValue: "B"}),
onNext(400, {newValue: "Bl"}),
onNext(490, {newValue: "Bla"}),
onNext(650, {newValue: "Blah"}),
onNext(1100, {newValue: "Blah Blah"}),
onCompleted(1500)
);
//This will run your observable using the test scheduler
//It returns an observer which you can query for making assertions
var result = test_scheduler.startWithTiming(function () {
return testObservable
.map(function (data) {
return data.newValue;
})
.distinctUntilChanged()
.filter(function (searchText) {
return searchText.length > 2;
})
.throttleFirst(350, test_scheduler);
},
50, //This tells the function when to call the above factory function and create the observable
200, //This is when to subscribe to your observable
1500 //This is when to dispose of the subscription
);
//Here we can check if the observable performed as expected.
//Because of the filter the first two should be rejected, so the first one would occur at 490
//650 occurs too soon and is rejected, so finally we get the last message and an onCompleted()
result.messages.should.eql([onNext(490, "Bla"), onNext(1100, "Blah Blah"), onCompleted(1500)]);
A couple things to note: 1) I think you may actually want throttleFirst now instead of throttle. Since I think that is the behavior generally used for this use case 2) TestScheduler is at its core a virtualTimeSheduler, meaning that it won't do anything until its clock is advanced. You can do this either like in the example above or directly by using the provided advanceBy and advanceTo methods. 3) I didn't show the example with your flatmap call, since it is really not relevant to the overall chain, if you add it back in I would suggest mocking the service item, otherwise you will have an external time dependency.
Thanks for taking the time on this example, that's really helpful
I have the following simple code that fires a request off to a service with a throttle:
I'm having a problem "mocking" the scheduler with a test scheduler, eliminating the absolute throttle timeout.
Is it possible to provide an example showing how do this? Thanks