SyntaxError: Unexpected token import with Jest + r

2019-07-01 13:06发布

问题:

My snapshot test is failing with react-native. I have followed few solutions but nothing worked. Error I am facing is:

/Users/USER_NAME/Projects/project_name/node_modules/react-native-animated-ellipsis/dist/AnimatedEllipsis.js:1 (function (exports, require, module, __filename, __dirname) { import React, { Component } from 'react'; ^^^^^^ SyntaxError: Unexpected token import

  at node_modules/babel-core/lib/transformation/file/options/option-manager.js:178:20

In my package.json:

"jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.js?$": "babel-jest"
    },
    "testPathIgnorePatterns": [
      "/node_modules/",
      "Tests/Setup.js"
    ],
    "testMatch": [
      "**/**/__tests__/**/*.js?(x)",
      "**/?(*.)(spec|test).js?(x)"
    ],
    "transformIgnorePatterns": [
      "node_modules/(?!(react-native|rent-react-native|react-native-navigation|react-native-vector-icons|react-native-maps|react-native-animated-ellipsis)/)"
    ]
  },

and .babelrc

{
  "presets": ["react-native"],
  "env": {
    "test": {
      "presets": ["env", "react-native"],
      "plugins": ["react-native-animated-ellipsis"],
      "only": [
        "./**/*.js",
        "node_modules/react-native-animated-ellipsis"
      ]
    }
  }
}

回答1:

I'm not sure why you'd like to apply a babel transformation on one of your project's dependency but following the error message, even if you wanna apply a babel transform on react-native-animated-ellipsis, you should probably do it on the src and exclude the dist folder.