Shlomy Z
Shlomy Z

Reputation: 331

Testing NGRX/effect with jest - test is always passing

I created a test of an effect but the test is always passing

@Injectable()
export class myEffects {
  @Effect()
  getEffect$ = this.actions$.pipe(
    ofType(MyActionTypes.Get),
    switchMap((action: GetAction) =>
      this.myService
        .get()
        .map((data) => new GetSuccessAction(data))
        .catch((res) => of(new GetFailedAction(res)))
    )
  );

  constructor(private actions$: Actions<MyActions>, public myService: MyService) {}
}
describe('myEffects', () => {
  let actions$: ReplaySubject<any>;
  let effects: myEffects;
  let myService = {
    get: jest.fn()
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        myEffects,
        provideMockActions(() => actions$),
        {
          provide: MyService,
          useValue: myService
        }]
    });
    effects = TestBed.get<myEffects>(myEffects);
  });

  it('aaa', () => {
    const data = {};

    myService.get.mockReturnValue(data);

    actions$ = new ReplaySubject(1);
    actions$.next(new GetAction());

    effects.getEffect$.subscribe((action) => {
      expect(action).toEqual({
        type: MyActionTypes.GetFailed,
        payload: data
      });
    });
  });
});

The test should pass only when the type that the effect trigger is GetSuccess, but setting the expect type to GetFailed - the test is also passed. please help. thanks

Upvotes: 1

Views: 1057

Answers (1)

The Fabio
The Fabio

Reputation: 6250

The problem is that in your test the subscription body is never called.

Because this is an asynchronous test, you need to use the callback/helper done, like this:

 it('aaa', async done => { // <== here
    const data = {};

    myService.get.mockReturnValue(data);

    actions$ = new ReplaySubject(1);
    actions$.next(new GetAction());

    effects.getEffect$.subscribe((action) => {
      expect(action).toEqual({
        type: MyActionTypes.GetFailed,
        payload: data
      });
      done(); // <== and here, the test will only pass when the subscription is called
    });
  });

Upvotes: 2

Related Questions