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

React Native运行yarn test遇@react-native-cookies/cookies相关错误

解决React Native中@react-native-cookies/cookies测试时的iOS依赖错误

问题场景

执行yarn test时抛出错误:

Invariant Violation: @react-native-community/cookies: Add RNCookieManagerIOS.h and RNCookieManagerIOS.m to your Xcode project

导入语句为:

import CookieManager from '@react-native-cookies/cookies';

解决方案

方案1:Mock原生模块(测试环境专用)

jest运行时无原生iOS环境,直接mock掉@react-native-cookies/cookies模块即可绕过错误:

  • 单个测试文件mock:在测试文件顶部添加以下代码
    jest.mock('@react-native-cookies/cookies', () => ({
      get: jest.fn().mockResolvedValue({}),
      set: jest.fn().mockResolvedValue(true),
      clearAll: jest.fn().mockResolvedValue(true),
      // 根据业务需求添加其他需要的方法
    }));
    
  • 全局mock:
    1. 在项目根目录创建__mocks__/CookieManager.js文件
    2. 文件内容:
      const CookieManager = {
        get: jest.fn().mockResolvedValue({}),
        set: jest.fn().mockResolvedValue(true),
        clearAll: jest.fn().mockResolvedValue(true),
      };
      export default CookieManager;
      
    3. 修改jest.config.js,添加模块映射:
      module.exports = {
        // 其他已有配置
        moduleNameMapper: {
          '@react-native-cookies/cookies': '<rootDir>/__mocks__/CookieManager.js',
        },
      };
      

方案2:确保iOS原生依赖配置正确(若需真机/模拟器运行)

如果是自动链接未生效,可手动补全配置:

  • 执行pod安装:
    npx pod-install ios
    
  • 手动添加文件到Xcode:
    1. 打开iOS项目的.xcworkspace文件
    2. 右键点击项目目录,选择「Add Files to [你的项目名]」
    3. 找到node_modules/@react-native-cookies/cookies/ios/路径下的RNCookieManagerIOS.h和RNCookieManagerIOS.m文件,添加到项目
    4. 确保文件已关联到目标target,重新编译项目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:02:09