我正在使用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());
选项1: - 对我有用的东西:
import NavigationService from '<your-path>/NavigationService';
beforeEach(() => {
NavigationService.navigate = jest.fn();
});
在我的测试文件中。
选项2: - 更好的版本
重要的是你通过jest.mock('../../app/utils/NavigationService');
激活模拟这必须放在你的测试文件的顶部直接在导入后面