【问题标题】:React Native tests failing, missing babel transformsReact Native 测试失败,缺少 babel 转换
【发布时间】:2019-12-19 13:12:11
【问题描述】:

我想测试一个基于default guides 创建的 React Native 应用程序,所以它非常简单并且没有任何更改 w.r.t。初始测试配置。唯一的区别似乎是它使用npm 而不是yarn(所以它有一个package-lock.json)。

这里是package.json

{
  "name": "foo",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-gesture-handler": "^1.5.2",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "^7.7.4",
    "@babel/runtime": "^7.7.4",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.7.1",
    "jest": "^24.9.0",
    "license-checker": "^25.0.1",
    "metro-react-native-babel-preset": "^0.57.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

测试文件__tests__/App-test.js 非常简单(并且是自动生成的):

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', () => {
  renderer.create(<App />);
});

我收到此错误:

➜ npm test
> jest

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

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /node_modules/@foo/bar/src/main.js:24
    export function milliseconds(timeoutInMilliseconds) {
    ^^^^^^

    SyntaxError: Unexpected token 'export'

现在,我真的不明白为什么它不能“开箱即用”。 Other guides 也提到了相同的步骤。

添加.babelrc

{ 
  "presets": ["react-native"]
}

产生错误:

Cannot find module 'babel-preset-react-native' from '/'
    - If you want to resolve "react-native", use "module:react-native"

      at Function.module.exports [as sync] (node_modules/resolve/lib/sync.js:74:15)
      at resolveStandardizedName (node_modules/@babel/core/lib/config/files/plugins.js:101:31)
      at resolvePreset (node_modules/@babel/core/lib/config/files/plugins.js:58:10)
      at loadPreset (node_modules/@babel/core/lib/config/files/plugins.js:77:20)
      at createDescriptor (node_modules/@babel/core/lib/config/config-descriptors.js:154:9)
      at node_modules/@babel/core/lib/config/config-descriptors.js:109:50
          at Array.map (<anonymous>)
      at createDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:109:29)
      at createPresetDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:101:10)
      at presets (node_modules/@babel/core/lib/config/config-descriptors.js:47:19)

已经有一个babel.config.js 文件,其内容如下(建议here):

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
};

我该怎么办?我见过this question,但 React 应用程序尚未升级,也没有丢失任何东西,AFAICT。请注意,当我使用 init 脚本创建一个全新的应用程序时,测试运行良好。

【问题讨论】:

    标签: react-native jestjs


    【解决方案1】:

    您正在使用"react-navigation": "^4.0.10",它使用react-native-gesture-handler。 Jest 对此一无所知。您必须模拟react-native-gesture-handler 并将react-navigation 添加到transformIgnorePatterns 或使用react-native-jest-mocks

    一些模拟react-native-gesture-handler的例子可以在这里找到:https://github.com/software-mansion/react-native-gesture-handler/issues/344

    package.json 中添加"files": ["jest/setup.js"],"。另外transformIgnorePatterns 必须包括react-navigation-stack@react-native-communityreact-native-gesture-handlerreact-navigation

    package.json:

    "files": [
      "jest/setup.js"
    ],
    "jest": {
      "preset": "react-native",
      "transform": {
        "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
      },
      "setupFiles": ["./jest/setup.js"],
      "testPathIgnorePatterns": [
        "/node_modules/"
      ],
      "transformIgnorePatterns": [
        "node_modules/(?!(jest-)?react-native|react-navigation-stack|@react-native-community|react-native-gesture-handler|react-navigation|@react-navigation/.*)"
      ]
    }
    

    jest/setup.js:

    import { NativeModules as RNNativeModules } from "react-native";
    RNNativeModules.UIManager = RNNativeModules.UIManager || {};
    RNNativeModules.UIManager.RCTView = RNNativeModules.UIManager.RCTView || {};
    RNNativeModules.RNGestureHandlerModule = RNNativeModules.RNGestureHandlerModule || {
      State: { BEGAN: "BEGAN", FAILED: "FAILED", ACTIVE: "ACTIVE", END: "END" },
      attachGestureHandler: jest.fn(),
      createGestureHandler: jest.fn(),
      dropGestureHandler: jest.fn(),
      updateGestureHandler: jest.fn(),
    
    };
    RNNativeModules.PlatformConstants = RNNativeModules.PlatformConstants || {
      forceTouchAvailable: false
    };
    
    jest.mock('react-native/Libraries/Animated/src/NativeAnimatedHelper');
    

    现在运行 jest,它应该可以通过测试。我使用 react-navigation 创建了一个带有示例 RN 0.61 应用程序的存储库,该应用程序通过了开玩笑测试:https://github.com/clytras/RNJestTest

    或者您可以尝试react-native-jest-mocks,但我还没有尝试使用 RN 0.61。

    【讨论】:

    • 谢谢!我不可能在任何地方读到这个……我确实读得更远了,现在我在node_modules/react-native/Libraries/Utilities/warnOnce.js:15 中得到一个错误:SyntaxError: Missing initializer in const declaration,见i.stack.imgur.com/2rcWW.png——有什么想法吗?
    • @slhck 检查更新的答案。我在 Github 上上传了一个非常简单的示例 repo,它可以工作,请查看。
    • 谢谢,这就是解决方案。我现在得到一个不同的错误,但我知道为什么。奇怪的是,记录如此糟糕。你会认为它可以或多或少地自动拾取所有这些。
    猜你喜欢
    • 2019-12-09
    • 2022-10-20
    • 1970-01-01
    • 2018-12-17
    • 2017-01-20
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多