Vitest - Testing Observables
02/01/2025, SatRead Observables Values Correctly
As the JavaScript world have adopted promises to handle asynchronous events, it would be no surprise that Vitest would also support promises.
Stepping away for Vitest for a moment, the general method of testing RxJS observables was through marble diagram testing such as using TestScheduler, but the TestScheduler is more suited for testing the order of emitted values from observables.
If your observable only emits one final value, it is more suitable to convert the observable to a promise and check the return value in Vitest as shown below
import { lastValueFrom } from 'rxjs';
// Depending on your application, you might need to switch
// out lastValueFrom with firstValueFrom for the conversion to work.
const promiseResults = await lastValueFrom(returnsObservable());
expect(result).toBe(valueExpected);
The returnsObservable
function should return an observable that emits a value. This means that there should be a value that can be read in the argument
of the subscribe function. The map
function can achieve the task of returning such a value for the observable to emit as a final messsage.
const returnsObservable = function() {
return anObservable$
.pipe(
map(() => {
return 'a value';
})
);
}
const myObservable$ = returnsObservable();
myObservable$
.subscribe((theValue) => {
console.log(theValue);
});