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

使用Jest和react-native-testing-library测试时提示RNEncryptedStorage未定义

报错原因

Jest 测试默认运行在 Node.js 环境,不会加载 React Native 原生模块,react-native-encrypted-storage 依赖原生层实现,因此在测试环境中会抛出未定义错误。

可行解决步骤
  • 第一步:创建全局 Mock 文件
    在项目根目录新建__mocks__文件夹(如果不存在的话),在文件夹内创建react-native-encrypted-storage.js文件,写入以下 Mock 代码:
    export default {
      setItem: jest.fn(() => Promise.resolve()),
      getItem: jest.fn(() => Promise.resolve(null)),
      removeItem: jest.fn(() => Promise.resolve()),
      clear: jest.fn(() => Promise.resolve()),
      getAllKeys: jest.fn(() => Promise.resolve([]))
    }
    
  • 第二步:配置 Jest 识别 Mock
    你可以二选一配置:
    • 单测试文件生效:在你的测试代码顶部添加一行 jest.mock('react-native-encrypted-storage') 即可
    • 全局所有测试生效:打开你的 Jest 配置文件(一般是jest.config.js或者package.json中的jest字段),添加以下配置:
      module.exports = {
        // 保留你已有的其他配置
        moduleNameMapper: {
          '^react-native-encrypted-storage$': '<rootDir>/__mocks__/react-native-encrypted-storage.js'
        },
        transformIgnorePatterns: [
          'node_modules/(?!(react-native|react-native-encrypted-storage)/)'
        ]
      }
      
  • 第三步:重新运行测试
    执行你的测试命令即可,后续如果需要测试和加密存储相关的业务逻辑,还可以自定义 Mock 方法的返回值来验证逻辑正确性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 14:24:04