React Native运行yarn test遇@react-native-cookies/cookies相关错误
问题场景
执行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:
- 在项目根目录创建
__mocks__/CookieManager.js文件 - 文件内容:
const CookieManager = { get: jest.fn().mockResolvedValue({}), set: jest.fn().mockResolvedValue(true), clearAll: jest.fn().mockResolvedValue(true), }; export default CookieManager; - 修改
jest.config.js,添加模块映射:module.exports = { // 其他已有配置 moduleNameMapper: { '@react-native-cookies/cookies': '<rootDir>/__mocks__/CookieManager.js', }, };
- 在项目根目录创建
方案2:确保iOS原生依赖配置正确(若需真机/模拟器运行)
如果是自动链接未生效,可手动补全配置:
- 执行pod安装:
npx pod-install ios - 手动添加文件到Xcode:
- 打开iOS项目的
.xcworkspace文件 - 右键点击项目目录,选择「Add Files to [你的项目名]」
- 找到
node_modules/@react-native-cookies/cookies/ios/路径下的RNCookieManagerIOS.h和RNCookieManagerIOS.m文件,添加到项目 - 确保文件已关联到目标target,重新编译项目
- 打开iOS项目的
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

