首页 > 解决方案 > React Native - Jest - Enzyme 抛出 Jest 无法解析错误

问题描述

当我想将 Jest 和 Enzyme 作为测试库添加到我的 React Native 项目时,我遇到了一个错误。这是我的代码:

//Button.spec.js
import React from 'react';
import { View } from 'react-native';
import { shallow } from 'enzyme';

const Test = () => <View />;

describe('SomeComponent component', () => {
  it('Shallow rendering', () => {
    const wrapper = shallow(<Test />);
  });
});

//jest/setup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

//babel.config.js
module.exports = () => ({
  presets: ['module:metro-react-native-babel-preset'],
  plugins: ['transform-flow-strip-types']
});

//jest.config.json
{
    "preset": "react-native",
    "collectCoverage": true,
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "transform": {
        "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
    },
    "setupFiles": [
        "<rootDir>/jest/setup.js"
    ],
    "transformIgnorePatterns": [
        "/node_modules/(?!react-native|).+\\.js$"
    ],
    "coveragePathIgnorePatterns": [
        "/node_modules/",
        "/jest"
    ]
}

当我跑步时npm test。它会抛出这样的错误:

/src/components/common/__test__/Button.spec.js: Unexpected token (5:19)

      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:
        3 | import { shallow } from 'enzyme';
        4 | 
      > 5 | const Test = () => <View />;
          |                    ^
        6 | 
        7 | describe('SomeComponent component', () => {
        8 |   it('Shallow rendering', () => {

你们有什么建议来解决这个问题吗?我应该添加我在 node_modules 中使用的任何库transformIgnorePatterns吗?或者是否缺少设置步骤?

标签: javascriptreactjsreact-nativejestjsenzyme

解决方案


推荐阅读