【问题标题】:React-native-modal - Unexpected Token with Jest using TransformIgnorePatternsReact-native-modal - 使用 TransformIgnorePatterns 的带有 Jest 的意外令牌
【发布时间】:2019-08-29 22:58:31
【问题描述】:

我正在尝试使用 Jest 在 React Native 组件上运行测试。 使用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 |       );

有什么想法吗?

【问题讨论】:

    标签: react-native jestjs babeljs babel-jest


    【解决方案1】:

    更新(修复)

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

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

    由于我只将这一行添加到本地环境.bablerc,这导致了如何编译 babel JSX react native 组件的问题。

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

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 2017-03-24
      • 1970-01-01
      • 2018-09-16
      • 2018-10-27
      • 2021-03-26
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      相关资源
      最近更新 更多