react-native - React Native 测试失败,缺少 babel 转换

标签 react-native jestjs

我想测试我基于 default guides 创建的 React Native 应用程序,所以它非常简单,并且没有任何更改。初始测试配置。唯一的区别似乎是它使用 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-navigation": "^4.0.10",它使用react-native-gesture-handler。杰斯特对此一无所知。您必须模拟 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 应用程序的存储库,该应用程序已通过 Jest 测试: https://github.com/clytras/RNJestTest

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

关于react-native - React Native 测试失败,缺少 babel 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59410500/

相关文章:

javascript - React/Jest setUp 测试以定义 windows 对象

javascript - 如何配置 Jest 测试框架以在 Nuxt.js 中使用?

javascript - 发生构建错误 ReferenceError : describe is not defined > During now. sh 部署

node.js - npm 启动失败 : at FSEvent. FSWatcher._handle.onchange (内部/fs/watchers.js:135:12)

javascript - ComponentDidUpdate 用法和超出最大更新深度

android - 在 native react 中使用 map 时出错

reactjs - 开 Jest 如何检查 spy 函数中被调用的 spy 函数?

react-native - 将原子作为函数参数传递时的试剂性能问题

reactjs - 模块 redux 不存在于 haste 模块映射中

reactjs - Enzyme Shallow 渲染实例不继承 props