babbaggeii babbaggeii - 26 days ago 13
Javascript Question

How to test RxJS events

I'm handling a mouseover event using

Observable.fromEvent()
, with various chained operators. How would I go about unit testing this?

export const bindMouseover = (link) => Observable.fromEvent(link, 'mouseover')
.filter(event => Nav.hasSubNav(event.target))
.map(event => Nav.getSubNav(event.target))
.filter(target => !Nav.elementIsVisible(target))
.subscribe((target) => {
Nav.hideElements(subNavs);
Nav.showElement(target);
});

Answer

There's a chapter on testing RxJS chains in the RxJS 4 documentation but the principles applies to RxJS 5 as well: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/testing.md

If you want to unit test RxJS custom operators or operator chains there's official documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/writing-marble-tests.md (However, this document doesn't tell you where you can import features listed there in your own code).

Also, have a look at how RxJS is tested itself. For example testing map() operator (btw, these are mocha tests). Note how Hot and Cold Observables are made with this short notation cold('--1--2--3--|') and then compared with the expected '--x--y--z--|' using expectObservable that comes from TestScheduler.

If you wanted to use also the short notation with cold(...), hot(...) and others you'd need to grab the source code, compile it with npm run build_test and then use the same options for mocha as the original. See package.json and the default options for mocha in default.opts. I'm not aware of any easier solution right now.

The short notation just makes things easier and more readable but you don't need it in fact. You can use the regular test Observables (TestScheduler, ColdObservable and HotObservable) already since they're part of the standard rxjs package. https://github.com/ReactiveX/rxjs/tree/master/src/testing (node_modules/rxjs/testing)

Also see: How to debug Observable values in Angualr2 / Typescript?

Comments