【问题标题】:Jest + @testing-library/react-native Error: ReferenceError: You are trying to `import` a file after the Jest environment has been torn downJest + @testing-library/react-native 错误:ReferenceError:您正在尝试在 Jest 环境被拆除后“导入”文件
【发布时间】:2021-08-25 05:30:42
【问题描述】:

概述:

我制作了一个自定义输入组件,我可以在必要时添加道具和可选道具,但在运行npm run test 时遇到错误(见下文)。我正在使用jest@testing-library/react-native

错误:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. 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 `Input`.
        at Input (/Users/jefflewis/Documents/Computer-Programming/Projects-Libraries/unsion/unison-ui-react-native/src/components/inputs/Input.tsx:24:20)

我的尝试:

  • 我的所有其他测试都有效,但输入测试无效,我似乎无法查明错误。
  • 我已尝试移除某些道具

Input.test.tsx:

// Imports: Dependencies
import React from 'react';
import renderer from 'react-test-renderer';
import { cleanup } from '@testing-library/react-native';

// Imports: Components
import Input from '../Input';

// React Native Testing Library: Cleanup (Unmounts Component And Destroys Container)
afterEach(cleanup);

// Tests: Input
describe('Input', () => {
  // Renders Component
  it('renders component', () => {
    renderer.create(<Input placeholder="Placeholder" value="Value" onChangeText={() => console.log('Hi')} />);
  });
});

Input.tsx:

// Imports: Dependencies
import React, { useEffect, useState, useRef } from 'react';
import { Dimensions, StyleSheet, Text, TextInput, View } from 'react-native';

// Imports: Styles
import { defaultStyles } from '../../styles/styles';

// Imports: TypeScript Types
import { IInputProps } from '../../types/inputTypes';

// Screen Dimensions
const { width } = Dimensions.get('window');

// Component: Input
const Input: React.FC<IInputProps> = ({
  value,
  onChangeText,
  placeholder,
  placeholderTextColor,
  label,
  darkMode,
  autoCapitalize,
  autoCompleteType, // Android Only
  autoCorrect,
  autoFocus,
  blurOnSubmit,
  caretHidden,
  clearButtonMode, // iOS Only
  clearTextOnFocus, // iOS Only
  dataDetectorTypes, // iOS Only
  defaultValue,
  editable,
  enablesReturnKeyAutomatically, // iOS Only
  keyboardType,
  maxLength,
  multiline,
  numberOfLines, // iOS Only
  onSubmitEditing,
  returnKeyType,
  secureTextEntry,
  spellCheck, // iOS Only
  textAlign,
  textContentType, // iOS Only
  // passwordRules, // iOS Only
}): JSX.Element => {
  // React Hooks: State
  const [text, setText] = useState<string>('');

  // React Hooks: Refs
  const textInputRef: React.RefObject<TextInput> = useRef(null);

  // React Hooks: Lifecycle Methods
  useEffect(() => {
    // Set State
    setText(value);
  }, [value]);

  // Render Label
  const renderLabel = (): JSX.Element | undefined => {
    // Check If Prop Exists
    if (label) {
      return <Text style={darkMode ? styles.labelTextDark : styles.labelTextLight}>{label}</Text>;
    }
  };

  return (
    <View style={styles.container}>
      <>{renderLabel()}</>

      <TextInput
        ref={textInputRef}
        style={darkMode ? styles.inputTextDark : styles.inputTextLight}
        placeholder={placeholder}
        placeholderTextColor={placeholderTextColor ? defaultStyles.colorDarkLabelTertiary : defaultStyles.colorLightLabelTertiary}
        value={text}
        onChangeText={onChangeText}
        autoCapitalize={autoCapitalize || 'none'}
        autoCompleteType={autoCompleteType || 'off'} // Android Only
        autoCorrect={autoCorrect}
        autoFocus={autoFocus}
        blurOnSubmit={blurOnSubmit}
        caretHidden={caretHidden}
        clearButtonMode={clearButtonMode || 'never'} // iOS Only
        clearTextOnFocus={clearTextOnFocus} // iOS Only
        dataDetectorTypes={dataDetectorTypes || 'none'} // iOS Only
        defaultValue={defaultValue}
        editable={editable}
        enablesReturnKeyAutomatically={enablesReturnKeyAutomatically} // iOS Only
        keyboardAppearance={darkMode ? 'dark' : 'light'} // iOS Only
        keyboardType={keyboardType || 'default'}
        maxLength={maxLength || 1000}
        multiline={multiline}
        numberOfLines={numberOfLines || 1} // Android Only
        onSubmitEditing={onSubmitEditing}
        returnKeyType={returnKeyType || 'done'}
        secureTextEntry={secureTextEntry}
        spellCheck={spellCheck} // iOS Only
        textAlign={textAlign || 'left'}
        textContentType={textContentType || 'none'} // iOS Only
      />
    </View>
  );
};

// Styles
const styles = StyleSheet.create({
  container: {
    height: 'auto',
    width: width - defaultStyles.marginExtraLarge,
    marginBottom: defaultStyles.marginMedium,
  },
  labelTextLight: {
    color: defaultStyles.colorDarkLabelSecondary,
    fontSize: defaultStyles.fontSizeFootnoteSmall,
    fontWeight: defaultStyles.fontWeightSemiBold,
    letterSpacing: defaultStyles.fontLetterSpacingFootnote,
    textTransform: 'uppercase',
  },
  labelTextDark: {
    color: defaultStyles.colorLightLabelSecondary,
    fontSize: defaultStyles.fontSizeFootnoteSmall,
    fontWeight: defaultStyles.fontWeightSemiBold,
    letterSpacing: defaultStyles.fontLetterSpacingFootnote,
    textTransform: 'uppercase',
  },
  inputTextLight: {
    height: 40,
    fontSize: defaultStyles.fontSizeSubheading,
    color: defaultStyles.colorLightLabel,
    borderColor: defaultStyles.colorLightBorder,
    borderBottomWidth: StyleSheet.hairlineWidth,
    // textOverflow: 'ellipsis',
  },
  inputTextDark: {
    height: 40,
    fontSize: defaultStyles.fontSizeSubheading,
    color: defaultStyles.colorDarkLabel,
    borderColor: defaultStyles.colorDarkBorder,
    borderBottomWidth: StyleSheet.hairlineWidth,
    // textOverflow: 'ellipsis',
  },
});

// Exports
export default Input;

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    能够在玩笑设置中使用这个模拟来解决它:

    jest.mock('@react-navigation/native/lib/commonjs/useLinking.native', () => ({
      default: () => ({getInitialState: {then: jest.fn()}}),
      __esModule: true,
    }));
    

    来源:github

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 2018-11-20
      • 2022-01-06
      • 2021-11-03
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2022-10-01
      相关资源
      最近更新 更多