Observable with pairwise not firing in test

1.2k views Asked by At

Trying to test a method that is using pairwise.

Method:


this.x$.pipe(pairwise()).subscribe((x) => {
      const [previous, current] = x;
      this.store.dispatch(actionThatIWantToFire({ appId: current }));
    });

For demonstration purposes. I'm aware that I don't need pairwise. Pretend that I do.

test:

it(
    `should dispatch`,
    waitForAsync(() => {
      const dispatchSpy = jest.spyOn(store, 'dispatch');
      (component.x$ as Observable<any>) = cold('a---b|', {
        a: '123',
        b: '1234',
      });

      getTestScheduler().flush();
      expect(dispatchSpy).toHaveBeenCalledWith(
       actionThatIWantToFire,
      );
    }),
  );

But the code within the subscription never gets called. Only way to call it is to remove the pairwise. Any ideas?

1

There are 1 answers

1
Adama Traore On

From the RxJs Documentation :

Keep in mind that pairwise will not emit an initial value until the observable emits at least two values. This behavior can lead to confusion, as there will be no output and no error, but the observable might not be functioning as intended or is waiting for more values.

I found a workaround using startwith before using pairwise :

this.x$.pipe(
  startWith(INITIAL_VALUE),
  pairwise()
).subscribe((x) => {
  const [previous, current] = x;
  this.store.dispatch(actionThatIWantToFire({ appId: current }));
});