Jest 测试 React Native 不能在模块外使用 import 语句

Jest Testing React Native cannot use import statement outside of a module

我一直在尝试找出如何在尝试使用 React Native 运行 我的 Jest 测试时修复以下错误:

FAIL tests/App-test.js ● Test suite failed to run

/home/marijkebuurman/Desktop/sport-data-valley-questionnaire-app/node_modules/react-native/index.js:13
import typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';
^^^^^^

SyntaxError: Cannot use import statement outside a module

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.<anonymous> (node_modules/@react-navigation/native/lib/commonjs/useBackButton.tsx:3:1)

package.json

{
  ...
  "dependencies": {
    "@react-native-community/datetimepicker": "^2.3.2",
    "@react-native-community/masked-view": "^0.1.8",
    "@react-native-community/push-notification-ios": "^1.1.1",
    "@react-native-firebase/app": "^6.7.1",
    "@react-native-firebase/auth": "^6.7.1",
    "@react-native-firebase/firestore": "^6.7.1",
    "@react-navigation/bottom-tabs": "^5.2.6",
    "@react-navigation/material-top-tabs": "^5.1.9",
    "@react-navigation/native": "^5.1.5",
    "@react-navigation/stack": "^5.2.10",
    "axios": "^0.19.2",
    "prop-types": "^15.7.2",
    "react": "16.11.0",
    "react-native": "0.62.2",
    "react-native-background-fetch": "^3.0.5",
    "react-native-elements": "^1.2.7",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-image-picker": "^2.3.1",
    "react-native-keychain": "^5.0.1",
    "react-native-push-notification": "^3.1.9",
    "react-native-reanimated": "^1.8.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.4.0",
    "react-native-tab-view": "^2.14.0",
    "react-native-vector-icons": "^6.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/preset-flow": "^7.10.1",
    "@babel/runtime": "^7.6.2",
    "@bam.tech/react-native-make": "^2.0.0",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.4.2",
    "babel-plugin-module-resolver": "^4.0.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.4",
    "react-native-dotenv": "^0.2.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "./jest.setup.js"
    ],
    "moduleNameMapper": {
      "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-)?react-native|react-navigation)"
    ]
  }
}

我试图通过使用transformIgnorePatterns 尝试忽略 react-navigation 来解决我的 package.json 文件中的问题,但这没有用。

.babelrc

{
  "presets": [
    "module:metro-react-native-babel-preset",
    "module:react-native-dotenv",
    "@babel/preset-flow"
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "cwd": "babelrc",
        "root": [
          "./src"
        ],
        "extensions": [
          ".js",
          ".ios.js",
          ".android.js"
        ],
        "alias": {
          "api": "./src/api",
          "assets": "./src/assets",
          "services": "./src/services",
          "styles": "./src/styles",
          "components": "./src/components",
          "app": "./src"
        }
      }
    ]
  ]
}

我还安装了 @babel/preset-flow 并将其添加到我的 .babelrc 文件中的预设中,因为我在某处读到这可能有帮助,但没有成功。

我的测试

// import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', async () => {
  renderer.create(<App />);
});

测试本身几乎是默认提供的 React Native Jest 测试。我已经评论了 React Native 的 import 语句,因为这在 运行ning 测试时给出了类似的错误。当取消注释该行时,测试仍然给出关于 AccessibilityInfo import 语句的错误,但是没有提到 @react-navigation 而是关于 ScriptTransformer.js.

我的猜测是这一切与我的 babel 配置有关,但我一直无法弄清楚。

我尝试了很多对我的 .babelrc 文件的更改,但我最终通过将我的 .babelrc 文件转换为当前看起来像的 babel.config.js 文件来修复错误这个:

module.exports = function(api) {
  api.cache(true);
  return {
    presets: [
      'module:metro-react-native-babel-preset',
      'module:react-native-dotenv',
      '@babel/preset-flow',
    ],
    plugins: [
      [
        'module-resolver',
        {
          root: ['./src'],
          extensions: ['.js', '.ios.js', '.android.js'],
          alias: {
            api: './src/api',
            assets: './src/assets',
            services: './src/services',
            styles: './src/styles',
            components: './src/components',
            app: './src',
          },
        },
      ],
      ['transform-class-properties'],
    ],
  };
};

除此之外,我在 __mocks__ 目录中为不同的包添加了很多模拟,例如 react-native-firebase。我很确定我添加的模拟文件没有参与修复我的问题中的错误,但是通过添加模拟文件修复了其他类似的错误。

我所说的类似错误是指错误消息类似于:

SyntaxError: Cannot use import statement outside a module

在某些情况下,修复此错误需要添加库,错误向 transformIgnorePatterns 投诉,该库位于文件 jest.config.js.

// jest.config.js 
module.exports = {
  preset: 'react-native', 
    setupFilesAfterEnv: [
    // 1. specific setup for react-native 
    '@testing-library/jest-native/extend-expect',

    // 2. global setup & mocking for some services: 
    './jest.setup.js',

    // 3. mocking for more services: 
    './__mocks__/react-native-firebase.js',
    "./__mocks__/@react-native-community/google-signin.ts", 
  ],
  // 4. You need to add the library to the RegEx below <- Problem Fix
  //    For example, if the error was related to "react-native-elements", you need to add it to the list (as shown below.) 
  transformIgnorePatterns: ["node_modules/(?!((jest-)?react-native|react-native-elements|@react-native(-community)?)/)"], 
}

"react-native": "0.66.4"

"@testing-library/jest-native": "^4.0.4"
"@testing-library/react-native": "^9.0.0"
"babel-core": "^7.0.0-bridge.0"
"babel-jest": "^27.4.6"
"jest": "^27.4.7"
"metro-react-native-babel-preset": "^0.66.2"