I have a very simple periodic activity which is scheduled by RxJS 5 and I'm a bit curious about how to unit test this type of code using RxJS 5:
start() {
this._subscription = Observable
.interval(this._interval, SchedulerProvider.getScheduler())
.subscribe(_ => this.doSomething());
}
stop() {
this._subscription.unsubscribe();
}
What I tried is to stub my SchedulerProvider.getScheduler
function to return a new TestScheduler()
during my tests (by default it just returns undefined
so the production code just uses the default scheduler) - and then try to setup virtual "ticks" for the interval:
myTestSchedulerInstance.createColdObservable('xxxxxxxx', {x: 1}); // tick ten times
unitUnderTest.start();
myTestSchedulerInstance.flush();
... assert that doSomething() should be called 10 times ....
But it doesn't work. I guess createColdObservable
and createHotObservable
just returns a new observable based on the marble-syntax input string - but this doesn't affect my interval.
I went through the docs and I'm a bit confused now about the marble testing in RxJS 5, because the examples in the docs (and everywhere else) look like this:
- in the first step: create a test scheduler
- then create a cold/hot observable using this scheduler
- your unit under test applies some operators on the created observable - which produces another observable
- then you assert on the resulting observable using
expectObservable
But my use-case is different. I don't want to return the Observable.interval
, because I'm only interested in the side-effect of my subscription. Is it possible to write such a test using RxJS 5?
The only alternatives which I see right now:
- use sinon's fake timers
- inside
start()
, map the side effect to the interval and after subscribing to it, return the observable containing the side effect -> and use it in the assertion usingexpectObservable
But each solution seems to be a bit messy.