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

React Native Jest测试导入Redux时RNLocalize模块找不到问题

React Native Detox测试导入阶段RNLocalize报错问题

场景与问题

React Native应用构建后,计划在Jest(Detox)测试文件中修改Redux状态的某个变量,因无法在测试中编写完整逻辑,故在Redux状态新增变量并尝试在应用运行时修改。但测试尚未启动,在导入阶段即抛出RNLocalize相关错误。

相关代码与配置

测试文件(login.test.js)

import { by, device, element, waitFor } from 'detox';
import configureStore from '../../src/createStore';

describe('Example', () => {
  const store = configureStore();
  const { dispatch } = store;
  beforeAll(async () => {
    console.log(JSON.stringify({ store }, null, 2));
    console.log(JSON.stringify({ state: store.getState() }, null, 2));
    await device.launchApp();
  });
});

Jest配置(jest.config.json)

{
  "maxWorkers": 1,
  "testTimeout": 120000,
  "verbose": true,
  "rootDir": "../../",
  "reporters": ["detox/runners/jest/reporter"],
  "globalSetup": "detox/runners/jest/globalSetup",
  "globalTeardown": "detox/runners/jest/globalTeardown",
  "testEnvironment": "detox/runners/jest/testEnvironment",

  "cacheDirectory": ".jest/cache",
  "moduleFileExtensions": ["js", "jsx", "json", "svg"],
  "modulePathIgnorePatterns": ["lib/"],
  "preset": "react-native",
  "testPathIgnorePatterns": ["\\.snap$", "<rootDir>/node_modules/"],
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)x?$",
  "transform": {
    "^.+\\.jsx?$": "babel-jest",
    "^.+\\.svg$": "jest-transformer-svg"
  },
  "transformIgnorePatterns": [
    "node_modules/(?!(@ptomasroos|axios|(jest-)?@?react-native|react-native-modal|react-navigation|react-navigation-tabs|react-navigation-redux-helpers|react-native-safari-view|react-native-linear-gradient|react-native-blur|react-native-animatable|react-native-wkwebview-reborn|react-native-safe-area-view|react-native-popup-menu|redux-persist|react-native-localize|react-native-reanimated)/)"
  ]
}

完整错误信息

Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'RNLocalize' could not be found. Verify that a module by this name is registered in the native binary.

     6 | import React from 'react';
  >  7 | import * as RNLocalize from 'react-native-localize';
       | ^

    at invariant (node_modules/invariant/invariant.js:40:15)
    at Object.getEnforcing (node_modules/react-native/Libraries/TurboModule/TurboModuleRegistry.js:43:12)
    at Object.getEnforcing (node_modules/react-native-localize/src/NativeRNLocalize.ts:18:36)
    at Object.require (node_modules/react-native-localize/src/module.ts:1:1)
    at Object.require (node_modules/react-native-localize/src/index.ts:1:1)

解决方法

报错原因是Jest的JavaScript测试环境中不存在react-native-localize的原生模块实现,必须通过Mock来规避这个问题。

方案1:在测试文件中直接Mock

在测试文件的最顶部(导入任何依赖之前)添加Mock代码,模拟react-native-localize的核心方法:

// 必须放在所有导入语句之前
jest.mock('react-native-localize', () => ({
  getLocales: jest.fn(() => [{ languageCode: 'en', countryCode: 'US' }]),
  getCountry: jest.fn(() => 'US'),
  // 根据项目实际使用的RNLocalize方法补充Mock实现
}));

import { by, device, element, waitFor } from 'detox';
import configureStore from '../../src/createStore';

// 后续测试代码不变
describe('Example', () => {
  const store = configureStore();
  const { dispatch } = store;
  beforeAll(async () => {
    console.log(JSON.stringify({ store }, null, 2));
    console.log(JSON.stringify({ state: store.getState() }, null, 2));
    await device.launchApp();
  });
});

方案2:全局Mock(适用于多个测试文件)

如果多个测试文件都依赖react-native-localize,可以在Jest的全局配置文件中统一添加Mock:

  1. 在项目根目录创建jest.setup.js文件,写入Mock代码:
jest.mock('react-native-localize', () => ({
  getLocales: jest.fn(() => [{ languageCode: 'en', countryCode: 'US' }]),
  getCountry: jest.fn(() => 'US'),
  // 补充其他需要的方法
}));
  1. 修改jest.config.json,在配置中添加setupFilesAfterEnv字段:
{
  // 原有配置不变
  "setupFilesAfterEnv": ["<rootDir>/jest.setup.js"]
}

额外说明

  • Mock的方法需要与项目中实际调用的react-native-localize方法保持一致,避免后续测试中因方法不存在而报错。
  • 若configureStore内部依赖了使用RNLocalize的模块,必须确保Mock代码在导入configureStore之前执行,否则仍会触发原生模块查找错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:05:43