React Native,jest测试失败,无效的挂接调用

2ledvvac  于 2023-03-03  发布在  React
关注(0)|答案(1)|浏览(130)

我得到这个错误与我的测试谁能帮助?

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
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

      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();
});
pxyaymoc

pxyaymoc1#

您需要在测试文件中使用自己的Provider Package <SearchLocationInput {...newProps} />组件(当应用程序通过模拟器运行时,与真实的的Provider不同),因为theme变量与ThemeContext挂钩。

const themeContextMock: ThemeContextProps = {
  // Your theme object props
}

const setup = (props) => {
  const newProps = {
    ...defaultProps,
    ...props
  };
  return render( 
    <ThemeContext.Provider value={themeContextMock}>
      <SearchLocationInput {...newProps} />
    </ThemeContext>
  )
}

相关问题