【问题标题】:How to test race condition of a redux observable epic如何测试 redux 可观察史诗的竞争条件
【发布时间】:2019-03-20 20:10:06
【问题描述】:

我有一个用例,我需要取消 Ajax 调用并在史诗中执行其他操作。在 redux-observable 文档中有 an example 完全符合我的需要。但是,当我尝试在我的史诗中测试赛车条件时,“取消”似乎不起作用。

示例代码如下:

import { ajax } from 'rxjs/ajax';

const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action => race(
    ajax.getJSON(`/api/users/${action.payload}`).pipe(
      map(response => fetchUserFulfilled(response))
    ),
    action$.pipe(
      ofType(FETCH_USER_CANCELLED),
      map(() => incrementCounter()),
      take(1)
    )
  ))
);

我的史诗结构和上面的例子一样,就像:

initViewsEpic = (action$, state$, { ajaxGet }) => action$
  .ofType(INIT_VIEWS)
  .pipe(
    mergeMap(() => race(
      ajaxGet('/api/views/...')
        .pipe(
          switchMap(response => of(
            initViewsFulFilled(response),
            taskCompleted(INIT_VIEWS),
          )),
          startWith(taskInProgress(INIT_VIEWS)),
          catchError(error => of(
             notification(),
             taskCompleted(INIT_VIEWS),
           )),
        ),
      action$.pipe(
        ofType(INIT_VIEWS_CANCEL),
        map(() => taskCompleted(INIT_VIEWS),
        take(1),
      ),
    )),
  );

我的测试是这样的:

test('should ignore the ajax call response when INIT_VIEWS_CANCEL action is fired', (done) => {
    const action$ = ActionsObservable.of({ type: 'INIT_VIEWS' }, { type: 'INIT_VIEWS_CANCEL' });
    const ajaxGet = () => timer(3000);

   initViewsEpic(action$, state$, { ajaxGet })
      .pipe(toArray()).subscribe((actions) => {
        expect(actions).toEqual([
          {
            type: 'TASK_IN_PROGRESS',
            payload: { id: 'INIT_VIEWS' },
          },
          {
            type: 'TASK_COMPLETED',
            payload: { id: 'INIT_VIEWS' },
          },
        ]);
        done();
      });
  });

我想由于INIT_VIEWS_CANCEL 动作同步跟随INIT_VIEWS 动作,它应该“赢得”ajaxGet 并且不应该有任何initViewsFulFilled 出去。但是这个测试的结果总是返回 initViewsFulFilled 作为我史诗的第二个输出动作(我正在使用 jest 来测试史诗)。

我在测试中有什么做错了吗?如果是这样,我怎样才能在 redux-observable 的史诗中正确地测试这种竞争条件?

【问题讨论】:

    标签: rxjs jestjs race-condition redux-observable


    【解决方案1】:

    我会说我会给出一个测试 redux observable 史诗的建议(那就是 我做了什么)——在rxjs/testing中使用TestScheduler。这样我们就不必为处理其他测试框架的 ascyn 东西而摸不着头脑

    希望这可以帮助和我遇到同样问题的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-10
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2019-01-23
      相关资源
      最近更新 更多