关于redux-observable史诗的Stub catch

时间:2016-12-07 18:57:52

标签: rxjs sinon rxjs5 redux-observable rxjs-dom

我试图测试一个rxjs观察者的catch函数,但是catch永远不会运行。

test.js

it.only('On fail restore password', () => {
    sandbox = sinon.stub(Observable.ajax, 'post').returns(new Error());
    store.dispatch(restorePasswordVi('prueba'));
    expect(store.getActions()).toInclude({ success: false, type: SET_RESTORE_PASSWORD_SUCCESS });
  });

史诗请参阅https://redux-observable.js.org/

export function restorePasswordViEpic(action$: Observable<Action>, store: Store) {
  return action$
    .ofType(RESTORE_PASSWORD_VI)
    .switchMap(({ user }) => {
      store.dispatch(blockLoading(true));
      return Observable
       .ajax
       .post(`${config.host}/auth/restore-password`, { user })
         .map(() => setRestorePasswordSuccess(true))
         .catch(() => {
           return Observable.of(setMessage('Se ha producido un error por favor intente de nuevo.'));
         });
    });
}

1 个答案:

答案 0 :(得分:3)

Observable.ajax.post的存根需要返回引发错误的Observable

.returns(Observable.throw(new Error()));

所有在一起:

it.only('On fail restore password', () => {
  sandbox = sinon.stub(Observable.ajax, 'post').returns(Observable.throw(new Error()));
  store.dispatch(restorePasswordVi('prueba'));
  expect(store.getActions()).toInclude({ success: false, type: SET_RESTORE_PASSWORD_SUCCESS });
});

由于您现有的存根只返回一个Error对象本身(不是一个抛出错误的可观察对象),它应该会引发一个未被捕获的错误,例如:

Uncaught TypeError: Observable.ajax.post(...).map is not a function

如果您在运行测试时没有看到任何类似的错误,那么您可能会在某处静默地吞下错误,这是需要注意的事项。