Home > Mobile >  Fail ngrx effect unit test where the effect is marked with { dispatch: false } and the effect return
Fail ngrx effect unit test where the effect is marked with { dispatch: false } and the effect return

Time:11-14

Consider the following code:

loadProducts$ = createEffect(() =>
  this.actions$.pipe(
  ofType(requestLoadProducts),
  switchMap(action =>
    this.service.load().pipe(
      map(data => loadProducts({products: data}))
    ))
  )
, { dispatch: false });

As you can see, adding { dispatch: false } is a mistake made by the developer (since the effect supposed to return and dispatch an action), which mistake was caught only by manualy testing the application, since the unit test trying to cover this effect passed.

describe('loadProuct$', () => {
  it('should return loadProducts', (done) => {
    actions$ = of(requestLoadProducts);
    effects.loadProducts$.subscribe((result) => {
      expect(result).toEqual(
        loadProducts({
          products: [{ id: 1, name: 'asd', price: '2', image: 2 }],
        })
      );
      done();
    });
  });
});

I know that { dispatch: false } doesn't change the flow, it just prevents actually dispatching the returned action under-the-hood. Unfotunately it means that such mistake can't be catched in unit test.

Do you know any solution to properly cover this in unit test?

CodePudding user response:

You can use getEffectsMetadata to verify dispatch is set to false. This method returns the config of an effect.

import { getEffectsMetadata } from @ngrx/effects;

expect(getEffectsMetadata(effectClass).effectProperty$.dispatch).toBe(false);
  • Related