React + Redux-Observable 超时弹珠测试

React + Redux-Observable Timeout Marble Testing

我正在使用 React 和 Redux Observables 创建一个网络应用程序,我想为我的 epics.

之一的超时场景创建一个单元测试

这是史诗:

export const loginUserEpic = (action$: ActionsObservable<any>, store, { ajax, scheduler }): Observable<Action> =>
  action$.pipe(
    ofType<LoginAction>(LoginActionTypes.LOGIN_ACTION),
    switchMap((action: LoginAction) =>
      ajax({
        url,
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: { email: action.payload.username, password: action.payload.password },
      }).pipe(
        timeout(timeoutValue, scheduler),
        map((response: AjaxResponse) => loginSuccess(response.response.token)),
        catchError((error: Error) => of(loginFailed(error))),
      ),
    ),
  );

这是我的测试:

  it('should handle a timeout error', () => {
    // My current timeout value is 20 millseconds
    const inputMarble = '------a';
    const inputValues = {
      a: login('fake-user', 'fake-password'),
    };

    const outputMarble = '--b';
    const outputValues = {
      b: loginFailed(new Error('timeout')),
    };

    const ajaxMock = jest.fn().mockReturnValue(of({ response: { token: 'fake-token' } }));
    const action$ = new ActionsObservable<Action>(ts.createHotObservable(inputMarble, inputValues));
    const outputAction = loginUserEpic(action$, undefined, { ajax: ajaxMock, scheduler: ts });

    // I am not sure what error to expect here...
    ts.expectObservable(outputAction).toBe(outputMarble, outputValues);
    ts.flush();
    expect(ajaxMock).toHaveBeenCalled();
  });

我预计 Epic 会抛出超时错误,因为我的超时值为 20 毫秒,而 Observer 在发出值之前延迟了 60 毫秒。然后我会接受这个错误并在最后比较它以使测试通过。

很遗憾,没有抛出超时错误。我做错了什么吗?

您在调用 ajax() 后在链中使用 timeout,其中 returns 只是 of({ ... }) (ajaxMock) 所以 timeout永远不会触发,因为 of 立即发出。

如果您想测试 timeout 运算符,您需要将 delay 添加到 ajaxMock:

const ajaxMock = () => of({ response: { token: 'fake-token' } }).pipe(delay(30, ts));

这是您的演示:https://stackblitz.com/edit/rxjs6-demo-pha4qp?file=index.ts

如果登录请求从 60 开始并且您添加了 30 延迟,那么在 80 时您将收到 TimeoutError。

[0: Object
  frame: 80
  notification: Notification
  error: undefined
  hasValue: true
  kind: "N"
  value: Object
    error: Error
      message: "Timeout has occurred"
      name: "TimeoutError"
]