gpt4 book ai didi

javascript - Jest 模拟导航服务

转载 作者:行者123 更新时间:2023-11-28 20:49:13 24 4
gpt4 key购买 nike

我正在使用 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:- 对我有用的:

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'); 激活模拟很重要,这必须放在测试文件的顶部直接落后于进口

关于javascript - Jest 模拟导航服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com