React-native-modal-使用TransformIgnorePatterns玩笑的意外令牌

时间:2019-04-08 18:14:10

标签: react-native jestjs babel babel-jest

我正在尝试在React Native组件上使用Jest运行测试。 使用react-native-modal。我是Jest和常规单元测试的新手,所以不确定如何解决此问题。

我什至添加: 设置中的transformIgnorePatterns属性,但问题仍然相同。

我的目标是测试Modal组件的属性。

实际测试:

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

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

test('renders BottomModalComponent.js', () => {
  const tree = renderer.create(<BottomModalComponent isVisible={false} />).toJSON();
  expect(tree).toMatchSnapshot();
});

.babelrc 设置

// File-relative configuration
{
  "plugins": [
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
  ],
  "presets": [
    "module:metro-react-native-babel-preset",
  ],
  "retainLines": true
}

依赖项:

  "dependencies": {
    "babel-core": "7.0.0-bridge.0",
    ...
},
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.4.0",
    "babel-eslint": "8",
    "babel-jest": "23.6.0",
    "babel-preset-react-native": "^4.0.1",
    "jest": "23.6.0",
    "jest-react-native": "^18.0.0",
    "metro-react-native-babel-preset": "^0.53.1",
    "react-test-renderer": "16.6.0-alpha.8af6728"
  },

babel.config.js

// Project-wide configuration
module.exports = {
  plugins: [
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
};

这是我的 package.json 在Jest设置中的样子:

"jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!(react-native|react-native-modal)/)"
    ]
  },

这是我运行npm run test

时的错误
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".

SyntaxError: /project_name/node_modules/react-native-modal/src/index.js: Unexpected token (470:8)

      468 |       this.props.useNativeDriver &&
      469 |       !this.state.showContent ? (
    > 470 |         <animatable.View />
          |         ^
      471 |       ) : (
      472 |         children
      473 |       );

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

更新(FIX)

调试一段时间后,我注意到问题是必须添加到项目范围的配置(babel.config.js)

"presets": [
    "module:metro-react-native-babel-preset",
  ]

由于我仅将此行添加到了本地环境.bablerc中,这导致了如何使JSX反应本机组件不可转换的问题。

因此,由于我的babel设置都相同,所以我可以摆脱 babel.config.js ,一切正常。