我在设置我的 jest 配置时遇到问题 react native 无法导入组件

Posted

技术标签:

【中文标题】我在设置我的 jest 配置时遇到问题 react native 无法导入组件【英文标题】:I'm having issues setting up my jest config react native Cannot Import Components 【发布时间】:2021-04-15 21:31:34 【问题描述】:

我遇到了与 babel configs 或 package.json 文件相关的问题...总之我无法从测试文件外部导入任何组件

这是错误:

 E:\.......\src\components\ButtonInstance.jsx:1
    ("Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest)import React from 'react';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import React from 'react';
      2 | import  render, fireEvent  from '@testing-library/react-native';
    > 3 | import ButtonInstance from '../src/components/ButtonInstance';
        | ^

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
  at Object.<anonymous> (__tests__/index.test.js:3:1)

这是我的测试文件:

import React from 'react';
import  render, fireEvent  from '@testing-library/react-native';
import ButtonInstance from '../example/src/ButtonInstance';

test('Button', () => 
  const onPressMock = jest.fn();
  const  getByText  = render(<ButtonInstance onPress=onPressMock />);
  fireEvent.press(getByText('Press me'));
  expect(onPressMock).toHaveBeenCalledTimes(1);
);

这是我的按钮实例组件

import React from 'react';
import  Text, TouchableHighlight  from 'react-native';

export default function ButtonInstance(onPress) 
  return (
    <TouchableHighlight onPress=onPress>
      <Text>Press me</Text>
    </TouchableHighlight>
  );

package.json 文件


  "name": "components-example",
  "description": "Example app",
  "version": "0.0.1",
  "private": true,
  "scripts": 
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start"
  ,
  "dependencies": 
    "@iconscout/react-native-unicons": "^1.0.3",
    "react": "16.13.1",
    "react-native": "0.63.4",
    "react-native-svg": "^9.5.3",
    "react-native-svg-transformer": "^0.14.3"
  ,
  "devDependencies": 
    "@babel/core": "^7.12.10",
    "@babel/runtime": "^7.12.5",
    "babel-plugin-module-resolver": "^4.0.0",
    "metro-react-native-babel-preset": "^0.64.0"
  

最后一个文件 babel.config.js

module.exports = 
  presets: [
    '@babel/preset-flow',
    '@babel/preset-react',
    [
      '@babel/preset-env',
      
        targets: 
          node: '10',
        ,
        bugfixes: true,
      ,
    ],
  ],
  plugins: ['@babel/plugin-proposal-class-properties'],
;

文件夹结构

|__ __tests__
         |__ index.test.js

|__ node_modules

|__ src
    |__ components
             |__ ButtonInstance.jsx

|__ babel.config.js

|__ package.json

【问题讨论】:

【参考方案1】:

我已经解决了这个与 babel 配置有关的问题,您可以将这些文件添加到您的应用程序中,这是新的 babel 工作配置文件(也许它可以帮助某人):

babel.config.js

module.exports = (api) => 
  api.cache(true);

  return 
    env: 
      development: 
        plugins: [
          [
            'module-resolver',
            
              root: ['./src'],
              extensions: ['.js', '.jsx'],
            ,
          ],
        ],
      ,
    ,
    presets: [['@babel/preset-env',  targets:  node: 'current'  ]],
  ;
;

还有开玩笑的配置文件:

jest.config.js

module.exports = 
  preset: 'react-native',
  moduleFileExtensions: ['js', 'jsx', 'json', 'svg'],
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)x?$',
  transform: 
    '^.+\\.jsx?$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
    '^.+\\.svg$': 'jest-svg-transformer',
  ,
  testPathIgnorePatterns: ['\\.snap$', '<rootDir>/node_modules/'],
  cacheDirectory: '.jest/cache',
  transformIgnorePatterns: [
    'node_modules/(?!(react-native|react-navigation|react-navigation-tabs|react-navigation-redux-helpers|react-native-safari-view|react-native-linear-gradient|react-native-blur|react-native-animatable|react-native-wkwebview-reborn|react-native-safe-area-view|react-native-popup-menu|redux-persist)/)',
  ],
;

【讨论】:

以上是关于我在设置我的 jest 配置时遇到问题 react native 无法导入组件的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Jest 测试样式

Jest 遇到了意外的令牌(React、Typescript、Babel、Jest 和 Webpack 设置)

在 react native + typescript 应用程序上运行 jest 时出错(Jest 遇到了意外的令牌)

使用 Jest 和 TestUtils 测试 React 表单提交

使用 React、Typescript 和 ES6 进行 Jest 测试

错误:当我在 React 中尝试使用 Jest 进行测试时,无法找到带有文本的元素