Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngrx effect unit test mulitple actions in mergemap

Tags:

ngrx

I am using ngrx library and have an effect like this

@Effect()
  loadCollection$: Observable<Action> = this.actions$
    .ofType(authAction.GET_USER)
    .startWith(new authAction.GetUserAction()) // call on app load
    .switchMap(() =>
      this.service.getUser()
        .mergeMap((user: User) => [
          new authAction.GetUserCompleteAction(user),
          new navigationAction.GetLinksCompleteAction(user.role)
        ])
    );

I am writing spec for it and it looks like this

 actions = new ReplaySubject(2);
        actions.next(new auth.GetUserAction());

        effects.loadCollection$.subscribe(result => {
            expect(service.getUser).toHaveBeenCalled();
            expect(result).toEqual(new navigation.GetLinksCompleteAction('test'));  --> this line fails
        });

How can I expect that multiple actions were called in the merge map.

like image 494
Angad Avatar asked Sep 18 '17 11:09

Angad


1 Answers

You can use jasmine-marbles to test conditions like mergeMap. See @ngrx/effects testing docs for examples: https://github.com/ngrx/platform/blob/master/docs/effects/testing.md

In your case the test would look something like this:

  actions = hot('-a', { a: new authAction.GetUserAction() });

  const expected = cold('-(bc)', { // the ( ) groups the values into the same timeframe
      b: new authAction.GetUserCompleteAction({}), // put whatever mock value you have here
      c: new navigationAction.GetLinksCompleteAction('test')
  };

  expect(effects.loadCollection$).toBeObservable(expected);

I would then split the test for checking expect(service.getUser).toHaveBeenCalled(); into a separate test case.

See https://github.com/ReactiveX/rxjs/blob/master/doc/writing-marble-tests.md for the hot/cold syntax.

like image 198
Silthus Avatar answered Oct 14 '22 03:10

Silthus