简体   繁体   中英

how to unit test rxjs timer in ngrx effect?

I have a working such an ngrx effect:

    public getData$ = createEffect(() => {
    const complete$ = this.store.select(currentUrl).pipe(filter((url) => (url ? url.includes('bad-url') : false)));

    return this.actions$.pipe(
      ofType(fromActions.GetData),
      switchMap(({ itemId }) => {
        return timer(0, 10000).pipe(
          switchMap(() => {
            return this.myService.getData(itemId).pipe(
              map((data) => fromActions.GetDataSucceeded({ data })),
              catchError((err) => of(fromActions.GetDataFailed({ err })))
            );
          }),
          takeUntil(complete$)
        );
      })
    );
    });

What it does: When GetData actions dispatched, make an service call to get data and after the first call make the same call every 10sec. If the url changes to 'bad-url' stop making the http call. So that works. However testing this code is not working, my test looks like:

      it('GetData', () => {
      jest.useFakeTimers();
      const mockRes = { some: 'data' }
      myService.getData.mockReturnValue(of(mockRes));

      actions$ = hot('-a-', {
        a: fromActions.GetData({ propertyId: 'some-property-1' }),
      });

      const expected = cold('-a-', {
        a: fromActions.GetDataSucceeded({ data: mockRes }),
      });

      expect(effects.getData$).toBeObservable(expected);
      jest.useRealTimers();
    });

that returns Received : [] in stead of expected..

Tried different type of testing approaching and nothing actually working... I would appreciate a lot any tips!

You will have to provide the test scheduler to the effect. https://ngrx.io/guide/effects/testing#effects-with-parameters

// effect
search$ = createEffect(() => ({
  // assign default values
  debounce = 300,
  scheduler = asyncScheduler
} = {}) =>
  this.actions$.pipe(
    ofType(BookActions.search),
    debounceTime(debounce, scheduler),
    ...
  )
);

// test
effects.search$({
  debounce: 30,
  scheduler: getTestScheduler(),
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM