如何测试返回多个操作的效果

时间:2017-03-10 16:58:29

标签: angular redux rxjs ngrx ngrx-effects

我有一个效果,它返回动作A然后动作B

@Effect() myEffect$: Observable <Action> = this.actions$
  .ofType('MY_ACTION')
  .switchMap(() => Observable.of(
    // subscribers will be notified
    { type: 'ACTION_ONE' },
    // subscribers will be notified (again ...)
    { type: 'ACTION_TWO' }
  ));

如何测试两个连续返回的动作?

it('should return action one then action two', () => {
  runner.queue(new myAction());
  const expectedResult = twoSuccesiveActions;
  sessionEffect.myEffect$.subscribe(result => {
    // how do I test those two succesively returned actions
    expect(result).toEqual(expectedResult);
  });
});

3 个答案:

答案 0 :(得分:0)

您可以使用take(1)一个,skip(1)一个:

it('should return action one then action two', () => {
  const expectedResult = twoSuccesiveActions;
  sessionEffect.myEffect$.take(1).subscribe(result => {
    // first action
    expect(result).toEqual(expectedResult);
  });

  sessionEffect.myEffect$.skip(1).take(1).subscribe(result => {
    // second action
    expect(result).toEqual(expectedResult);
  });

  runner.queue(new myAction());
});

无论如何,如果您不手动取消订阅以确保没有泄漏到其他测试中,我建议您使用take(1) ...

答案 1 :(得分:0)

像这样成对使用:

it('should return a ACTION_ONE && ACTION_TWO',
  inject([EffectService, EffectsRunner], (service: EffectService, runner: EffectsRunner) => {
    runner.queue({type: USER_SWITCH_ROLE});

    service.myEffect$
      .pairwise()
      .subscribe(([result1, result2]) => {
        expect(result1).toEqual({type: ACTION_ONE, payload: {}});
        expect(result2).toEqual({type: ACTION_TWO, payload: {}});
      });
  }));

答案 2 :(得分:0)

万一有人还在想如何做,这是另一种做事方式

effects.myEffect$
  .pipe(
    bufferCount(2)
  )
  .subscribe((emittedActions) => {
    /* You could also include here callings to services
        verify(myServiceMock.execute(anything()))
          .called();
    */
    expect(emittedActions.map((action) => action.type))
      .toEqual([
        myFirstAction,
        mySecondAction,
      ]);
    done();
  });