React Native中Jest测试触发Invalid hook call错误,求解决方案
React测试中Invalid Hook Call错误解决
错误信息
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app 32 | export default ThemeContext; 33 | > 34 | export const useThemeContext = () => useContext(ThemeContext);
组件代码
const SearchLocationInput = ({ onBackPress, onChangeText, value, placeholder, }) => { const theme = useThemeContext(); const formStyles = getFormsStyleObj({ theme: theme.theme }); const styles = getSearchLocationStyle({ theme: theme.theme }); const ContainerStyles = { ...styles.container, }; const inputContainerStyle = { ...formStyles.input, ...styles.inputContainerStyle, }; const InputProps = { value, inputContainerStyle, disabledInputStyle: styles.disabledInputStyle, rightIcon: SearchIcon, placeholder, placeholderTextColor: theme.colors.TEXTGREY, onChangeText, leftIcon: <BackButton onPress={onBackPress} />, leftIconContainerStyle: styles.leftIconContainerStyle, }; return ( <View style={ContainerStyles}> <Input {...InputProps} /> </View> ); };
测试代码
import React from 'react'; import { render, fireEvent } from '@/utils/testUtils'; import SearchLocationInput from '@/modules/maps/SearchLocationInput/SearchLocationInput'; jest.mock('@/services/AsyncStorageService') const defaultProps = { onPress: jest.fn(), } const setup = (props) => { const newProps = { ...defaultProps, ...props }; return render(<SearchLocationInput {...newProps} />) } const inputText = /Search for a location/i; test('it renders', () => { const { findByPlaceholder } = setup(); const input = findByPlaceholder(inputText); expect(input).toBeTruthy(); });
排查与解决步骤
- 检查React版本一致性:确保项目中react、react-native(或react-dom)版本完全匹配,无版本差异。执行
npm list react react-native(RN项目)或npm list react react-dom(web项目),确认是否存在多个React版本。 - 补充测试上下文包裹:组件依赖
ThemeContext,但当前测试未用ThemeContext.Provider包裹组件,导致自定义Hook调用useContext时出错。修改测试代码,给组件添加上下文包裹:// 导入ThemeContext与默认主题 import ThemeContext from '@/path/to/ThemeContext'; const defaultTheme = { theme: {}, // 填入你的实际主题结构 colors: { TEXTGREY: '#ccc' } }; const setup = (props) => { const newProps = { ...defaultProps, ...props }; return render( <ThemeContext.Provider value={defaultTheme}> <SearchLocationInput {...newProps} /> </ThemeContext.Provider> ) }; - 检查测试工具配置:确认
@/utils/testUtils中的render函数是否基于@testing-library/react-native或@testing-library/react的标准实现,避免自定义逻辑导致Hook调用异常。 - 清理重复依赖:若项目存在多个React副本,执行
npm dedupe合并重复依赖,或检查lock文件手动调整依赖版本,确保只有一份React包。
内容的提问来源于stack exchange,提问作者Bomber
相关产品推荐
相关产品推荐

