无法测试Redux可观察到的史诗

时间:2018-08-16 15:48:45

标签: javascript reactjs jestjs rxjs6

我打算为以下史诗写单元测试

// Actions
const actionCreator = actionCreatorFactory('PARENT_DIRECTORY');
export const fetchPage = actionCreator.async<Page, ParentPage>('FETCH_PAGE');

export const fetchParentDirectoryEpic: Epic = action$ =>
  action$.pipe(
    filter(fetchPage.started.match),
    mergeMap((action) => {
      return getDirectoryPage(action.payload).pipe(
        map(response => fetchPage.done({ params: action.payload, result: response.response })),
        catchError(error => of(fetchPage.failed({ params: action.payload, error: error })))
      );
    })
  );

我像下面那样嘲笑ge​​tDirectoryPage-

import { AjaxResponse, AjaxError } from 'rxjs/ajax';
import { Observable, of } from 'rxjs';

export function getDirectoryPage(page: any): Observable<AjaxResponse> {
  switch (page.index) {
    case 0:
      return Observable.create({'data': [], page: 0, pages: 1});
    default:
      return Observable.create(observer => {
        return new AjaxError('Something bad happened!', null, null);
      });
  }
}

以下是我的单元测试的样子-

describe('fetchParentDirectoryEpic Epic', () => {
    it('dispatches the correct actions when it is successful', async (done) => {
        const expectedOutputAction = outputAction;

        fetchParentDirectoryEpic(inputAction, initialState, null)
            .subscribe(actualOutputAction => {
                expect(actualOutputAction).toBe(expectedOutputAction)
                done()
            }
        );
    });
});

问题是,对fetchParentDirectoryEpic(inputAction, initialState, null)的调用导致了一个没有Subscribe方法的Observable。据我了解,该方法可用于ActionObservable,但无法使用有效负载创建其实例。

1 个答案:

答案 0 :(得分:0)

问题与我如何创建ExpectedOutputAction有关。应该是Action而不是ActionObservable

按以下方式设置ExpectedOutputAction之后,测试工作正常-

expectedOutputAction = {
  type: fetchPage.done.type, 
  result: {'data': [], page: 0, pages: 1}, 
  params: inputAction.payload
}