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

Jest测试React Native+styled-components报错:无法读取undefined的'Text'属性

解决Jest测试React Native应用时的TypeError: Cannot read properties of undefined (reading 'Text')错误

问题详情

测试基础App.tsx时出现如下报错:

FAIL  __tests__/App.test.tsx
  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'Text')

       9 | `;
      10 |
    > 11 | const DefaultText = styled.Text`
         |                            ^
      12 |   font-family: 'Inter';
      13 | `;
      14 |

      at Object.Text (src/ui/themes/Typography.ts:11:28)
      at Object.require (src/ui/themes/MainTheme.ts:2:1)
      at Object.require (mock/testmocks/styled-components.tsx:3:1)
      at Object.require (src/ui/styledComponents/Button.tsx:3:1)
      at Object.require (src/ui/styledComponents/index.ts:2:1)
      at Object.require (src/ui/screens/WelcomeScreen.tsx:6:1)
      at Object.require (src/App.tsx:4:1)

已验证通用测试(如下)运行正常,说明Jest基础配置无问题:

test('sample test', () => {
  expect(true).toBe(true);
});

测试文件App.test.tsx内容:

import React from 'react';
import {render} from '@testing-library/react-native';
import App from '@src/App';

describe('App', () => {
  it('renders without crashing', () => {
    render(<App />);
  });

  // Add more test cases as needed
});

完整App.tsx内容:

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import WelcomeScreen from '@src/ui/screens/WelcomeScreen';
import LoginScreen from '@src/ui/screens/LoginScreen';
import MainTabNavigator from '@navigation/MainTabNavigator';
import {AuthProvider} from '@context/AuthContext';
import {navigationRef} from '@navigation/navigationUtils';
import {ThemeProvider} from 'styled-components/native';
import {MainTheme} from '@themes/MainTheme';

const RootStack = createNativeStackNavigator();

const App = () => {
  return (
    <ThemeProvider theme={MainTheme}>
      <NavigationContainer ref={navigationRef}>
        <AuthProvider>
          <RootStack.Navigator>
            <RootStack.Screen name="Welcome" component={WelcomeScreen} />
            <RootStack.Screen name="LoginScreen" component={LoginScreen} />
            <RootStack.Screen
              name="MainTabNavigator"
              component={MainTabNavigator}
              options={{headerShown: false}}
            />
          </RootStack.Navigator>
        </AuthProvider>
      </NavigationContainer>
    </ThemeProvider>
  );
};

export default App;

解决方案

1. 修复styled-components的Mock文件

从错误栈可以看到,问题出在自定义的mock/testmocks/styled-components.tsx文件中,该文件没有正确模拟styled.Text属性。修改该文件,确保它完整模拟styled-components/native的API:

如果是使用jest.mock的方式:

import styled from 'styled-components/native';

jest.mock('styled-components/native', () => {
  const originalStyled = jest.requireActual('styled-components/native');
  return {
    ...originalStyled,
    Text: jest.fn(() => ({})),
    View: jest.fn(() => ({})),
    // 根据项目需求添加其他需要mock的styled组件
  };
});

如果是手动导出mock对象:

// mock/testmocks/styled-components.tsx
import React from 'react';

export const styled = {
  Text: jest.fn(() => ({})),
  View: jest.fn(() => ({})),
  // 项目中用到的其他styled组件
};

export const ThemeProvider = ({ children }: { children: React.ReactNode }) => children;

2. 验证模块导入路径

检查src/ui/themes/MainTheme.ts中导入styled的路径是否正确,确保是从styled-components/native导入,而非错误路径。

3. 确认Jest别名配置正确

检查jest.config.js中的moduleNameMapper,确保@themes、@src等别名已正确映射:

module.exports = {
  // 其他配置
  moduleNameMapper: {
    '^@src/(.*)$': '<rootDir>/src/$1',
    '^@themes/(.*)$': '<rootDir>/src/ui/themes/$1',
    '^@navigation/(.*)$': '<rootDir>/src/navigation/$1',
    '^@context/(.*)$': '<rootDir>/src/context/$1',
    // 其他项目别名
  },
};

4. 清除Jest缓存

缓存可能导致旧的mock代码生效,运行以下命令清除缓存:

jest --clearCache

内容的提问来源于stack exchange,提问作者Mike S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:54:52