angularrxjsjasminekarma-jasminengrx-effects

How to test if returned Observable is EMPTY


I have an effect that returns an EMPTY Observable in one case. I am trying to test this case, but I cant seem to figure out how to test EMPTY Observable? My code is as follows:

The effect:

   effect$ = createEffect(() =>
    this.actions$.pipe(
      ofType(someAction),
      mergeMap(([action]) => {
        if (someCondition) {
          return EMPTY <-- this is what I am trying to test
        }
        return someServiceCall.pipe(
          map((offers) => //dispatch some action,
          catchError((error: string) => // dispatch another action),
        )
      }),
    ),
  )

This is my unit test attempt, but it fails with

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL).

Take into consideration that the condition is already fulfilled in the test:

  it('should return EMPTY when ...', (done) => {
    actions$ = of(someAction)
    effects.effect$.subscribe((res) => {
      expect(res).toEqual(never)
      done()
    })
  })

I can make it work if the return is of(null) instead of EMPTY. But I would really like to know how to test this case.


Solution

  • It seems that we have a specific operation in RxJs that checks if an observable is empty. The operation is isEmpty()

    it('should return EMPTY when ...', (done) => {
        actions$ = of(someAction)
        effects.effect$.pipe(isEmpty()).subscribe( (res) => {
                                                   expect(res).toEqual(true)
                                                   done()
                                                  });
    

    res will be true only if observable does return with empty