React Native Navigation中无法Mock Props.navigation.navigate的问题
我有一个名为_navigateLogin的函数,代码如下:
export const _navigateLogin = (props: Props): () => void => () => { props.navigation.navigate(UnathorizedRoutes.LoginEmailPasswordPage); };
其props类型定义为:
export type NavigationProps = NativeStackScreenProps<UnauthorizedStackParams, UnauthorizedRoutes.IntroductionPage> export type Props = NavigationProps;
该函数运行正常,但测试时无法正确Mock。我尝试的Mock代码如下:
const mockRoute = { key: 'key', name: UnathorizedRoutes.IntroductionPage }; const mockProps = { navigation: { addListener: jest.fn(), canGoBack: jest.fn(), dispatch: jest.fn(), goBack: jest.fn(), isFocused: jest.fn(), setParams: jest.fn(), setOptions: jest.fn(), reset: jest.fn(), getId: jest.fn(), getParent: jest.fn(), getState: jest.fn(), jumpTo: jest.fn(), navigate: jest.fn(), removeListener: jest.fn() }, route: mockRoute };
调用_navigateLogin(mockProps)时出现类型错误,提示mock的navigation对象缺少StackActionHelpers中的replace、push、pop、popToTop属性,请问如何正确Mock这个函数?
解决方案
方法1:补全缺失的StackActionHelpers方法
直接在mock的navigation对象中添加类型要求的所有方法,用jest.fn()做默认实现即可:
const mockRoute = { key: 'key', name: UnathorizedRoutes.IntroductionPage }; const mockProps = { navigation: { addListener: jest.fn(), canGoBack: jest.fn(), dispatch: jest.fn(), goBack: jest.fn(), isFocused: jest.fn(), setParams: jest.fn(), setOptions: jest.fn(), reset: jest.fn(), getId: jest.fn(), getParent: jest.fn(), getState: jest.fn(), jumpTo: jest.fn(), navigate: jest.fn(), removeListener: jest.fn(), // 补全StackActionHelpers要求的方法 replace: jest.fn(), push: jest.fn(), pop: jest.fn(), popToTop: jest.fn() }, route: mockRoute };
这种方式严格匹配类型定义,不会出现类型报错。
方法2:使用类型断言简化Mock
如果只需要测试navigate方法,不想编写大量无用的mock函数,可以用类型断言跳过类型检查:
const mockRoute = { key: 'key', name: UnathorizedRoutes.IntroductionPage }; const mockProps = { navigation: { navigate: jest.fn() // 只保留测试需要用到的方法 }, route: mockRoute } as unknown as Props;
这种方式更简洁,适合快速编写单元测试,只关注核心逻辑的验证。
方法3:利用React Navigation官方测试工具
React Navigation提供了@react-navigation/testing库,可以快速生成符合类型的mock导航对象:
import { createMockNavigation } from '@react-navigation/testing'; const mockRoute = { key: 'key', name: UnathorizedRoutes.IntroductionPage }; const mockProps = { navigation: createMockNavigation(), route: mockRoute } as Props;
使用前需要先安装依赖:npm install --save-dev @react-navigation/testing,这种方式生成的导航对象自带所有必需的方法,无需手动补全。
内容的提问来源于stack exchange,提问作者Rokkies
相关产品推荐
相关产品推荐

