0

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?

Adam Waz
  • 21
  • 2

1 Answers1

0

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.

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • The result is the same, still throws error. – Adam Waz Jul 26 '22 at 12:54
  • Ok, check out my answer above. Try to use a `ReplaySubject` because a `BehaviorSubject` only emits the last value. – AliF50 Jul 26 '22 at 12:59
  • I want to get the last value, that's why I'm using BehaviorSubject. Using ReplaySubject(1) like this would produce the same error. const response$ = new ReplaySubject(1); response$.next(1); expectObservable(response$).toBe('ab', { a: 1, b: 2 }); response$.next(2); – Adam Waz Jul 26 '22 at 13:27
  • Ok, sorry, I am not sure. – AliF50 Jul 26 '22 at 13:49