ngrx 效果单元测试 mergemap 中的多个动作

ngrx effect unit test mulitple actions in mergemap

我正在使用 ngrx 库并且有这样的效果

@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)
        ])
    );

我正在为它编写规范,它看起来像这样

 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
        });

我怎么能想到在合并映射中调用了多个操作。

您可以使用 jasmine-marbles 来测试 mergeMap 等条件。有关示例,请参阅 @ngrx/effects 测试文档:https://github.com/ngrx/platform/blob/master/docs/effects/testing.md

在你的情况下,测试看起来像这样:

  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);

然后我会将用于检查 expect(service.getUser).toHaveBeenCalled(); 的测试拆分为一个单独的测试用例。

有关 hot/cold 语法,请参见 https://github.com/ReactiveX/rxjs/blob/master/doc/writing-marble-tests.md