【发布时间】:2018-10-31 10:06:39
【问题描述】:
我正在尝试测试这部史诗 https://github.com/zarcode/unsplashapp/blob/master/src/epics/photos.js 。问题是 map 在我运行测试时永远不会发生(我假设这意味着 Promise 永远不会解决),所以 photosSuccess 操作也永远不会发生:
export const loadPhotosToList = (action$: Observable<Action>, state$:
Object): Observable<Action> => {
const state = (photosFilter: PhotosFilter) => state$.value.photos[photosFilter];
return action$
// .ofType(ACTION.FETCH_PHOTOS_REQUESTED)
.pipe(
filter((a: Action) =>
a.type === ACTION.FETCH_PHOTOS_REQUESTED &&
((state(a.filter).loadingState === 'idle' && !state(a.filter).isLastPage) || a.refresh)),
switchMap((a) => {
const nextPage = !a.refresh ? state(a.filter).lastLoadedPage + 1 : 1;
const loadingAction = of(photosActions.photosLoading(a.filter, a.refresh));
const request = api.fetchPhotos({
page: nextPage,
per_page: perPage,
order_by: a.filter,
});
const requestAction = from(request)
.pipe(
// tap(data => { console.log("data", data); }),
map(data =>
photosActions.photosSuccess(
data,
a.filter,
nextPage,
data.length < perPage,
a.refresh,
)),
catchError(e => of(photosActions.photosFail(e.message, a.filter))),
);
// requestAction.subscribe(x => console.log("-------",x));
return loadingAction
.pipe(
concat(requestAction),
takeUntil(action$
.pipe(filter(futureAction => futureAction.type === ACTION.FETCH_PHOTOS_REQUESTED))),
);
}),
);
};
但是,如果我这样做,requestAction.subscribe 承诺会得到解决,我会在控制台日志中得到结果。
注意:仅当我运行此测试https://github.com/zarcode/unsplashapp/blob/master/src/epics/photos.test.js 时才会发生这种情况,应用程序代码工作正常,数据获取正常。
问题是:如何正确编写这个测试?
【问题讨论】:
-
当我运行你的测试套件时,我得到了
Invalid variable access: console并且所有 6 个都失败了,你知道为什么吗? -
您可以尝试将 return loadingAction 替换为 return Observable.fromPromise(loadingAction) 吗?
-
@TarunLalwani 可能跟node版本有关,我是在v9.2.0上运行的
-
@dentemm
photosActions.photosLoading(a.filter, a.refresh)是一个对象,而不是一个 Promise,因此使用 rxjs v6 执行 return Observable.fromPromise(loadingAction) 或 from(loadingAction) 会引发此类错误:TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. -
@zarcode,现在可以使用了,我在
10.1.0,可能有什么变化
标签: reactjs unit-testing react-native jestjs redux-observable