【问题标题】:Jest Testing React Native cannot use import statement outside of a moduleJest Testing React Native 不能在模块外使用 import 语句
【发布时间】:2020-06-02 18:11:40
【问题描述】:

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

FAIL tests/App-test.js ● 测试套件运行失败

/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 语句,因为这在运行测试时给出了类似的错误。当该行未注释时,测试仍然会给出有关 AccessibilityInfo 导入语句的错误,但没有提及 @react-navigation 而是提及 ScriptTransformer.js

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

【问题讨论】:

    标签: react-native jestjs babeljs


    【解决方案1】:

    我已经尝试对我的.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
    

    【讨论】:

      【解决方案2】:

      在某些情况下,修复此错误需要将库添加到文件jest.config.js 中的transformIgnorePatterns 中。

      // 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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-06
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 2022-11-11
        • 2021-04-22
        • 1970-01-01
        相关资源
        最近更新 更多