12

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"
    ]
  },
brass monkey
  • 5,841
  • 10
  • 36
  • 61
mfisher91
  • 805
  • 1
  • 8
  • 23
  • Can you include what version of Babel-jest you're using? the update from 23 to 24 broke a lot of my regex for transforms. They switched to micromatch 3 in that update – endqwerty Mar 11 '19 at 23:49

2 Answers2

14

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"]]
    }
  }
}
zgreen
  • 4,182
  • 1
  • 24
  • 19
  • I actually resolved this myself, but your answer is one of the issues I was having, so I'll mark it was correct :) – mfisher91 Sep 17 '19 at 13:28
4

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
Jared Wilber
  • 6,038
  • 1
  • 32
  • 35