开玩笑-SyntaxError:意外的标识符

时间:2019-03-11 18:35:57

标签: javascript node.js jestjs babel-jest

使用Jest对某些NodeJS函数进行测试,但它不喜欢import语句,例如import DatabaseController from '../util/database-controller'

我正在阅读,人们建议安装babel-jest并更新我的配置(如下),但是我没有任何运气。我想念什么?据我了解,它不理解import语句,因为这是es6的事情...

package.json的最好的部分:

"jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}"
    ],
    "resolver": "jest-pnp-resolver",
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "testMatch": [
      "<rootDir>/**/__tests__/**/*.{js,jsx}",
      "<rootDir>/**/?(*.)(spec|test).{js,jsx}"
    ],
    "testEnvironment": "jsdom",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.jsx?$": "babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ]
  },

2 个答案:

答案 0 :(得分:1)

这适用于我的简单设置:

devDependencies(在package.json中):

  "devDependencies": {
      "babel-eslint": "^10.0.3",
      "babel-preset-env": "^1.7.0",
      "jest": "^24.9.0",
      "parcel-bundler": "^1.12.3"
    }

我只是创建了一个babel.config.js,如下所示:

  // babel.config.js
  module.exports = {
    presets: [
      [
        '@babel/preset-env',
        {
          targets: {
            node: 'current',
          },
        },
      ],
    ],
  };

注意-确保在运行前清除缓存!

清除缓存:

  ./node_modules/.bin/jest --clearCache

答案 1 :(得分:0)

最近我发现我根本不需要babel-jest,只需使用@babel/preset-env和以下.babelrc就可以解决问题:

{
  "env": {
    "test": {
      "presets": [["@babel/preset-env"]]
    }
  }
}