reactjs - 开玩笑+@testing-library/react-native错误: ReferenceError: You are trying to `import` a file after the Jest environment has been torn down

标签 reactjs typescript react-native

概述:

我制作了一个自定义输入组件,必要时可以在其中添加 Prop 和可选 Prop ,但在运行 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)

我尝试过的:

  • 我的所有其他测试都有效,但输入测试不起作用,而且我似乎无法查明错误。
  • 我尝试删除某些 Prop

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')} />);
  });
});

输入.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;

最佳答案

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

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

来源:github

关于reactjs - 开玩笑+@testing-library/react-native错误: ReferenceError: You are trying to `import` a file after the Jest environment has been torn down,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68917290/

相关文章:

javascript - Base64 字符串图像未正确显示

javascript - 你会如何在 React-Relay 应用程序中上传文件?

javascript - 如何在 componentWillUnmount 中中止运行 async/await xmlHttpRequest?

animation - Angular 4 动画 - 不应用过渡持续时间

typescript - 设置 tsconfig "files"vs "include"的最佳实践?

android - 如何在 react-native 中更改应用程序的显示名称

reactjs - react : setState causes app crash

node.js - typescript + Express : Type 'typeof e' has no compatible call signatures

react-native - 这需要语法是什么?

ios - 如何在 React Native 中构造 POST 请求主体,而不是使用字符串化的 json,而是使用 json?