Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - SyntaxError: Unexpected identifier

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"
    ]
  },
like image 915
mfisher91 Avatar asked Mar 11 '19 18:03

mfisher91


2 Answers

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"]]
    }
  }
}
like image 119
zgreen Avatar answered Nov 10 '22 15:11

zgreen


This worked for my simple set-up:

devDependencies (in package.json):

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

I simply created a babel.config.js as follows:

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

Note - make sure to clear the cache before running!

Clear cache:

  ./node_modules/.bin/jest --clearCache
like image 2
Jared Wilber Avatar answered Nov 10 '22 15:11

Jared Wilber