Testing RxJS observables

When it comes to testing RxJS observables, there are many aspects worth observing. How many events have been emitted? Has the stream completed yet? Did it result in an error?

For advanced RxJS testing, RxJS Marble testing might be an interesting choice. Especially for asynchronous Obervables. However, RxJS marble testing can require quite some boilerplate code, and you have to get used to its marble syntax.

For simpler Observable testing, I created a small library which consists of Jasmine/Jest matchers.

Its syntax is quite easy.

const number$ = of(10, 20, 30);

expect(number$).toEqual(observable(
    next(10),
    next(20),
    next(30),
    completed()
));
expect(number$).not.toEqual(emptyObservable());
expect(number$).toEqual(completedObservable());

Please note, that this requires your stream to be synchronous: when the expect is executed, it subscribes to the stream and collects it in an array. If your stream is asynchronous, you may deal with limitations.

For Angular, you may want to use a fakeAsync helper to make asynchronous events like timers pass synchronously.

Head over to @dirkluijk/observable-matchers to use it. Happy testing!

Leave a Reply

Your email address will not be published. Required fields are marked *