You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Testing RxJS Observables With Jest
written by Jeff DelaneyHealth Check: This lesson was last reviewed on and tested with these packages:
- RxJS v6.2
Find an issue? Let's fix it
The snippet below shows you how to text asynchronous RxJS Observables with Jest. It’s probably easier than you think because you can simply
Testing a Single Emitted Value
Let’s imagine we have an Observable that should emit a string, which we can create with the of helper. The key to making this test work is passing it the the done
keyword, otherwise it will finish before the data is emitted.
You can then write your expectations inside of the the subscribe callback, then call done()
when you’re ready for the test to finish.
import { of } from 'rxjs'; |
The test above should fail because hola !== hello.
Testing a Complex Stream
RxJS is all about realtime streams. How might we test an observable the emits multiple values? For that, we will need to listen for the complete signal to be sent. If your Observable is a stream that never completes, you’ll also want to pipe in an operator to force completion, like takeWhile, otherwise Jest will timeout after 5000ms.
import { from } from 'rxjs'; |