我正在使用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))
)
)
);
navigate
是navigationService.navigate
,我是从redux-observables
的依赖项传递过来的。
测试如下:
const dependencies = {
ajax: ({ }) => of(mockedResponseFromAjax),
navigate: () => // ???
};
const result$ = loginEpic(action$, state$, dependencies).pipe(toArray());
答案 0 :(得分:0)
选项1:-对我有用的东西:
import NavigationService from '<your-path>/NavigationService';
beforeEach(() => {
NavigationService.navigate = jest.fn();
});
在我的测试文件中。
选项2:-更好的版本
重要的是,您必须通过jest.mock('../../app/utils/NavigationService');
激活模拟,这必须放置在测试文件顶部,导入文件的正后方