首页 > 解决方案 > React-native-modal - 使用 TransformIgnorePatterns 的带有 Jest 的意外令牌

问题描述

我正在尝试使用 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-nativejestjsbabeljsbabel-jest

解决方案


更新(修复)

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

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

由于我只将这一行添加到本地环境中.bablerc,这导致了如何将 babel 转换为 JSX 反应原生组件的问题。

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


推荐阅读