Testing BehaviorSubject with RxJS Marble

515 Views Asked by At

I have a problem with testing BehaviorSubject using rxjs marble.

Minimal reproduction:

scheduler.run(({ expectObservable }) => {
    const response$ = new BehaviorSubject(1);
    expectObservable(response$).toBe('ab', { a: 1, b: 2 });
    response$.next(2);
});

Error:

Expected $.length = 1 to equal 2.
Expected $[0].notification.value = 2 to equal 1.

In my case response$ is returned from some service's method. How can I test it?

1

There are 1 best solutions below

4
AliF50 On

Can you try switching the order and see if that helps?

scheduler.run(({ expectObservable }) => {
    const data$ = new ReplaySubject<number>();
    const response$ = new BehaviorSubject(1);
    response$.subscribe(num => data$.next(num));
    response$.next(2);
    expectObservable(data$).toBe('(ab)', { a: 1, b: 2 });
});

I think with the expectObservable, that's when the observable is subscribed and tested.

Edit

You need to use ReplaySubject instead of BehaviorSubject because BehaviorSujbect only returns the last emission of the Subject. Check out my edit above. I got inspired by this answer here: https://stackoverflow.com/a/62773431/7365461.