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

Expo测试时如何避免'AirGoogleMaps dir must be added to your xCode'错误?

解决react-native-maps Google Maps测试报错问题

问题原因

react-native-testing-library依赖的react-test-renderer在运行测试时默认以iOS为目标平台。而react-native-maps的Google Maps Provider在iOS环境下需要依赖原生的AirGoogleMaps目录,但Expo会自动处理原生配置,无需手动添加该目录到Xcode项目。不过测试运行在Node环境中,无法获取Expo的原生配置,因此触发了这个错误。

解决方案

方案1:Mock地图组件(推荐)

测试无需验证地图的原生渲染逻辑,只需关注组件自身的业务逻辑,因此可以直接Mockreact-native-maps组件:

jest.mock('react-native-maps', () => ({
  __esModule: true,
  default: jest.fn(() => null),
  // 若使用Marker等子组件,也需要Mock
  Marker: jest.fn(() => null),
}));

方案2:强制测试使用Android平台

通过修改Platform.OS让测试以Android环境运行,避开iOS的原生目录检查:

import { Platform } from 'react-native';
import { render } from '@testing-library/react-native';
import MapComponent from '../MapComponent';

test('渲染地图组件无报错', () => {
  // 临时切换为Android平台
  const originalOS = Platform.OS;
  Platform.OS = 'android';

  render(<MapComponent />);

  // 恢复原平台设置
  Platform.OS = originalOS;
});

或者使用jest的spyOn来更安全地Mock:

test('渲染地图组件无报错', () => {
  const mockPlatform = jest.spyOn(Platform, 'OS', 'get').mockReturnValue('android');
  
  render(<MapComponent />);
  
  // 清理Mock
  mockPlatform.mockRestore();
});

补充说明

Expo Go运行正常是因为Expo已经为你预配置了Google Maps所需的原生依赖,而测试环境是纯JS的Node环境,没有加载Expo的原生层,因此react-native-maps会按照标准React Native的要求检查iOS配置,导致报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:59