You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jest将@gorhom/portal的<Portal>组件Mock为View?

解决Jest中Mock @gorhom/portal 时的 PortalDispatchContext 错误

方法一:完整Mock @gorhom/portal 库

直接在测试文件顶部Mock整个库,不仅替换<Portal>为React Native的View,还要提供空的PortalProvider和必要的Context实现,避免Context为空报错:

jest.mock('@gorhom/portal', () => {
  const React = require('react');
  const { View } = require('react-native');
  
  // 创建空Context,避免组件读取时抛出空值错误
  const PortalDispatchContext = React.createContext({});
  const PortalProvider = ({ children }) => <View>{children}</View>;
  
  return {
    Portal: View,
    PortalProvider,
    PortalDispatchContext,
    // 若组件用到其他@gorhom/portal导出,需一并Mock
  };
});

方法二:Mock ViewWithPortal 组件

如果ViewWithPortal是你项目内的自定义组件,直接Mock它的实现,跳过Portal依赖:

// 替换为你的ViewWithPortal实际路径
jest.mock('../components/ViewWithPortal', () => {
  const { View } = require('react-native');
  return ({ children }) => <View>{children}</View>;
});

方法三:测试时手动包裹Mock的PortalProvider

若不想完全Mock组件,可在测试渲染时用Mock的PortalProvider包裹页面组件:

import { render } from '@testing-library/react-native';
import { PortalProvider } from '@gorhom/portal';

// 先将Portal组件Mock为View
jest.mock('@gorhom/portal', () => ({
  ...jest.requireActual('@gorhom/portal'),
  Portal: require('react-native').View,
}));

test('测试目标页面', () => {
  render(
    <PortalProvider>
      {/* 你的页面组件 */}
    </PortalProvider>
  );
});

关键注意点

  • 确保Mock覆盖所有用到@gorhom/portal的导出,比如BottomSheet内部若依赖Portal相关Context,必须保证这些Context有默认值或被正确Mock。
  • 优先选择完整Mock库的方式,避免遗漏内部依赖的Context导致报错。

内容的提问来源于stack exchange,提问作者lmasneri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:05:18