Jest渲染React Native组件报错:Element type is invalid
报错信息
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. 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
SplashScreen。
代码示例
src/screens/Splash/Splash.tsx
import React from 'react' import { View, Image } from 'react-native' import { styleSplash } from './styles' const SplashScreen = props => { const {} = props return ( <View style={styleSplash.main}> <Image style={styleSplash.logo} source={require('../../img/logo.png')} /> </View> ) } export default SplashScreen
tests/Splash-test.tsx
import React from 'react'; import 'react-native'; import SplashScreen from '../src/screens/Splash/Splash'; import { render, waitFor } from '@testing-library/react-native'; it('renders correctly', async () => { const tree = render(<SplashScreen />) await waitFor(() => { expect(tree).toMatchSnapshot(); }); });
问题详情
确认默认导出/命名导入逻辑无错误,VS Code未提示路径或导入问题,怀疑是依赖版本兼容问题。当前依赖版本:
"react": "18.2.0", "@testing-library/jest-native": "^5.4.3", "@testing-library/react": "^14.0.0", "@testing-library/react-native": "11.5.1", "@tsconfig/react-native": "^2.0.2", "babel-jest": "^29.7.0", "eslint": "^8.19.0", "jest": "^29.7.0", "jest-expo": "^49.0.0", "metro-react-native-babel-preset": "0.73.9", "react-dom": "^18.2.0", "react-test-renderer": "18.2.0",
已尝试方案
- 改用
react-test-renderer的renderer.create,可运行但持续出现act(...)包裹提示,未解决原报错 - 尝试多种导出/导入语法组合,报错无变化
- 升级
@testing-library/react-native到最新版,出现配置兼容提示,降级回11.5.1后回到原报错 - 在Jest配置中添加
"transform": {"^.+\\.tsx?$": "babel-jest"},无效果
可能的解决方向
检查样式文件导出
报错指向SplashScreen的render方法,有可能是styleSplash导出异常。确认./styles文件中是否正确导出styleSplash对象,比如是否存在默认导出误用命名导入、导出对象为空的情况。处理图片资源的测试兼容
Jest默认无法处理require导入的图片资源,可能导致Image组件渲染异常。可在Jest配置中添加图片mock:
在jest.config.js中加入:moduleNameMapper: { '\\.(png|jpg|jpeg|gif)$': '<rootDir>/__mocks__/imageMock.js' }然后在项目根目录创建
__mocks__/imageMock.js,内容为:module.exports = 'test-image-path';对齐依赖版本
当前@testing-library/react14.x版本与@testing-library/react-native11.5.1可能存在React 18适配的兼容问题。建议将@testing-library/react降级到13.x版本,同时参考@testing-library/react-native官方版本兼容表调整依赖:npm install @testing-library/react@13.4.0 --save-dev简化测试用例排查
暂时移除waitFor和快照断言,简化测试为:it('renders correctly', () => { render(<SplashScreen />); });观察是否仍报错,逐步排查是组件本身问题还是测试断言逻辑问题。
内容的提问来源于stack exchange,提问作者siberowl

