Jest - SyntaxError: Unexpected identifier

mfisher91 picture mfisher91 · Mar 11, 2019 · Viewed 7.4k times · Source

Doing some testing of some NodeJS functions using Jest, but it doesn't like import statements, e.g. import DatabaseController from '../util/database-controller'.

I've doing some reading and people suggested installing babel-jest and updating my config (below), but I've not had any luck. What am I missing? From what I understand, it doesn't understand import statements as it's an es6 thing...

Jest part of my 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"
    ]
  },

Answer

zgreen picture zgreen · Apr 28, 2019

Lately I find that I don't need babel-jest at all, and can get by simply with @babel/preset-env, and the following .babelrc:

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