Styled-components主题结合react-native testing-library测试报错theme.colors未定义
解决方案
1. 修复主题配置的语法错误
你当前的主题导出语法不符合ES规范,会导致导入的theme实际为undefined:
// 错误写法,不允许同时使用export default和const声明 export default const theme = { ... }
修改为以下任意一种正确写法即可:
// 写法1:先声明再导出 const theme = { // 你的主题配置内容 } export default theme // 写法2:直接导出对象 export default { // 你的主题配置内容 }
2. 修正ThemeProvider的导入路径
你使用的是React Native版本的styled-components,测试时也需要导入对应native版本的ThemeProvider,当前你导入的是web版本,无法向下传递主题参数:
// 错误写法:导入了web版的ThemeProvider import { ThemeProvider } from 'styled-components'; // 正确写法 import { ThemeProvider } from 'styled-components/native';
3. 检查Jest配置
如果修改完以上两点仍报错,检查jest.config.js中是否正确配置了转换规则:
module.exports = { // 其余配置保持不变 transform: { '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest', }, transformIgnorePatterns: [ 'node_modules/(?!(styled-components|react-native)/)', ], }
同时确认你没有在jest全局mock文件中错误重写了styled-components的ThemeProvider或者theme属性。
4. 排查依赖版本冲突
如果问题仍未解决,删除node_modules、package-lock.json/yarn.lock文件后重新安装依赖,确保项目中只有一个版本的styled-components,避免多版本冲突导致的上下文传递失效。
内容的提问来源于stack exchange,提问作者pbrune
相关产品推荐
相关产品推荐

