【发布时间】:2020-02-09 01:01:27
【问题描述】:
我对 redux-observable 还很陌生,所以我不确定这是一个真正的问题还是一个愚蠢的错误。
我正在尝试将测试添加到我为 React 应用程序编写的史诗中,但我无法测试它们。这是一个例子。
我的示例史诗:
const example = action$ =>
action$.pipe(
ofType('my_type'),
mergeMap(() => {
return { type: 'result_type'}
})
);
我试图以最简单的方式对其进行测试:
it('simple test', done => {
const action$ = ActionsObservable.of({ type: 'my_type'});
const state$ = null;
return myEpics.example(action$, state$)
.subscribe(actions => {
expect(actions).toEqual({ type: 'result_type'});
done();
})
});
使用此代码我收到以下错误:
TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
12 |
13 | return myEpics.example(action$, state$)
> 14 | .subscribe(actions => {
| ^
我正在使用 redux-observable 1.2.0、rxjs 6.5.3
我错过了什么吗?我看到了很多这种类型的例子,它们很有效。
编辑
我真正在做的(除了虚拟示例)是替换基于 redux-thunk Promise 的 api 中间件(对 ReST 端点进行许多异步调用)。 我能够让它工作,但关于测试我有点困惑。 我看到了弹珠图方法,以及订阅史诗的方法增加了期望,例如在 api 调用上,产生的动作。 我正在使用后者,但是,例如,对于返回多个动作的史诗,我只得到订阅中的第一个。
一个“复杂”的例子:
export const handleLogIn = (action$, state$) =>
action$.pipe(
ofType(authTypes.LOG_IN),
withLatestFrom(state$),
mergeMap(([{ payload: credentials}, { router }]) =>
from(ApiService.logIn(credentials))
.pipe(
mergeMap(authToken => of(authActions.set_auth_token(authToken), navigationActions.goTo(router.location.state ? router.location.state.pathname : baseRoutes.START),
catchError(message => of(authActions.set_auth_error(message)))
)
)
);
测试
it('should handle LOG_IN navigating to base path', done => {
const token = 'aToken';
const credentials = { username: 'user', password: 'password' };
const action$ = ActionsObservable.of(authActions.log_in(credentials));
const state$ = new StateObservable(new Subject(), { router: { location: { state: null }}});
spyOn(ApiService, 'logIn').and.returnValue(Promise.resolve(token));
authEpics.handleLogIn(action$, state$)
.subscribe(actions => {
expect(ApiService.logIn).toHaveBeenCalledWith(credentials);
expect(actions).toEqual([
authActions.set_auth_token(token),
navigationActions.go_to(baseRoutes.START)
]);
done();
});
});
测试失败,因为只有 authActions.set_auth_token 是唯一返回的操作。 我错过了什么吗?
【问题讨论】:
标签: rxjs jestjs redux-observable