fedexo
fedexo

Reputation: 62

How to write unit test for effect that after n times return a valid response?

I have to write Unit Test for this effect that is calling the service every 1 sec when it went in error. I need to test for example that after 3 times of calling a service, I'll receive a good response.

I tried some way to test but without any result.

This is the effect that I have to test:

@Effect()
  updateEffect$ = this.actions$.pipe(
    ofType(featureActions.ActionTypes.UPDATE_PRODUCT),
    switchMap((action: UpdateProduct) =>
      this.productService.getProducts().pipe(
        retryWhen((attempts) => attempts.pipe(delay(1000))),
        map((productsResponse: Products) =>
          productsResponse
            ? new featureActions.LoadProductSuccess(productsResponse)
            : new featureActions.LoadProductError(productsResponse)
        )
      )
    )
  );

This is the unit test that I did just to see the success scenario. What I want to test is the reload logic

 it('should return UpdateProduct if service response success ', () => {
    const action = new UpdateProduct('123456');
    const completion = new LoadProductSuccess(productsResponseMock);

    actions$ = hot('-a-', { a: action });
    const response = cold('-b', { b: productsResponseMock });
    const expected = cold('--c', { c: completion });

    productService.getProducts.and.returnValue(response);
    expect(effects.updateEffect$).toBeObservable(expected);
  });

Upvotes: 2

Views: 228

Answers (1)

Zazaeil
Zazaeil

Reputation: 4104

First of all, it is not a unit test. It is integration test: it tests a chain of various "units" (which have to be tested with help of unit tests).

Secondly, your test case sounds quite weird! How can you guarantee that after exactly 3 retries result gonna succeed?

The last but not the least: extract your retrying logic and test it as a separated unit. Extract error handling logic and test that it indeed calls your "retrier". And keep extracting units out of a chain you've described and test them independently!

Once those tests are there you might or might not decide to write an integration test. But that's a completely different story that barely overlaps with unit testing.

Upvotes: 1

Related Questions