嘲笑导航服务

时间:2018-12-28 04:42:25

标签: javascript testing mocking jestjs redux-observable

我正在使用react-navigation并在我的代码中调用该服务。尽管我不确定如何模拟navigate函数。这是我的代码:

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

这是我到目前为止所得到的:

export const loginEpic = (action$, state$, { ajax, navigate }) =>
  action$.pipe(
    ofType(LOGIN_REQUEST),
    map(() => state$.value),
    switchMap((options) =>
      ajax(options).pipe(
        pluck("response"),
        map((res) => loginSuccess(res)),
        tap((r) => navigate(ROUTES.DASHBOARD_SCREEN))
      )
    )
  );

navigatenavigationService.navigate,我是从redux-observables的依赖项传递过来的。

测试如下:

const dependencies = {
      ajax: ({ }) => of(mockedResponseFromAjax),
      navigate: () => // ??? 
    };
    const result$ = loginEpic(action$, state$, dependencies).pipe(toArray());

1 个答案:

答案 0 :(得分:0)

选项1:-对我有用的东西:

import NavigationService from '<your-path>/NavigationService';

beforeEach(() => {
    NavigationService.navigate = jest.fn();
});

在我的测试文件中。

选项2:-更好的版本

请参阅https://stackoverflow.com/questions/55319581/why-isn´t-mock-from-mock-folder-invoked-when-running-test-for-redux-action

重要的是,您必须通过jest.mock('../../app/utils/NavigationService');激活模拟,这必须放置在测试文件顶部,导入文件的正后方