babbaggeii babbaggeii - 1 year ago 141
Javascript Question

How to test RxJS events

I'm handling a mouseover event using

, with various chained operators. How would I go about unit testing this?

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

Answer Source

There's a chapter on testing RxJS chains in the RxJS 4 documentation but the principles applies to RxJS 5 as well:

If you want to unit test RxJS custom operators or operator chains there's official documentation: (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. (node_modules/rxjs/testing)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download