Jest导入node_modules模块返回空对象问题求助
测试ScrollOverflow组件时,Jest抛出错误:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of
ScrollOverflow.
调试发现react-native-linear-gradient、react-native-modal等第三方库被解析为{ default: {} }空对象,本地组件导入正常。以下是具体排查和解决方向:
1. 修正第三方库的转译配置
Jest默认不会转译node_modules中的文件,但很多React Native第三方库的源码未做预转译,导致解析异常。你当前的transformIgnorePatterns仅包含了@react-native、react-native、@react-native-firebase,需要把有问题的库加入白名单:
transformIgnorePatterns: [ 'node_modules/(?!(@react-native|react-native|@react-native-firebase|react-native-linear-gradient|react-native-modal)/)', ],
如果有大量同类型库,也可以用通用匹配简化:
transformIgnorePatterns: [ 'node_modules/(?!(@react-native|react-native|@react-native-firebase|react-native-.+)/)', ],
2. 为第三方库创建Jest Mock
如果转译方案无效,可直接为这些库创建Mock文件,避免加载真实源码:
- 在项目根目录的
__mocks__文件夹下创建react-native-linear-gradient.js:import React from 'react'; import {View} from 'react-native'; const LinearGradient = ({children, style, ...props}) => { return <View style={style}>{children}</View>; }; export default LinearGradient; - 同理创建
react-native-modal.js:import React from 'react'; import {View} from 'react-native'; const Modal = ({visible, children, ...props}) => { if (!visible) return null; return <View>{children}</View>; }; export default Modal;
Jest会自动识别并加载这些Mock文件,无需额外配置。
3. 检查TS测试配置的模块解析
确认tsconfig.spec.json中的moduleResolution配置,若使用NodeNext/Node16可能影响ES模块导入解析,可改为Node:
{ "compilerOptions": { "moduleResolution": "Node", // 其他原有配置... } }
同时检查moduleNameMapper,确保没有误将第三方库映射到错误路径。
4. 验证Babel配置兼容性
确保项目的babel.config.js包含React Native和TypeScript的正确预设:
module.exports = { presets: ['module:metro-react-native-babel-preset', '@babel/preset-typescript'], };
保证Babel能正确处理第三方库的ES语法。
5. 清除Jest缓存后重试
旧缓存可能导致异常残留,执行以下命令清除缓存后重新测试:
jest --clearCache npm test
内容的提问来源于stack exchange,提问作者gaurav5430

