"SyntaxError: Unexpected token export" using Jest with babel 7+

Viewed 1616

I'm trying to cover basic reducer with a test but it throws the error for export in my constants file:

 FAIL  jest/spec/reducers/RootReducer.spec.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    Details:

    project-root\js\src\constants\ActionTypes.js:2
    export const LOCALE_REQUEST = 'ROOT/LOCALE_REQUEST';
    ^^^^^^

    SyntaxError: Unexpected token export

      1 | 'use strict';
      2 |
    > 3 | import { LOCALE_REQUEST_SUCCESS, ROUTING_REQUEST_SUCCESS } from '/js/src/constants/ActionTypes';
        | ^
      4 |

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (jest/spec/reducers/RootReducer.spec.js:3:1)

I'm running the tests from 'project-root\tests' folder

The js files that I want to test are located in 'project-root\js' folder

I believe this is the reason for the bug. Because the file I'm trying to import is outside of the tests folder it looks like it's not being transpiled

this is my package.json:

{
  "name": "jest",
  "version": "0.0.0",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/plugin-transform-modules-commonjs": "^7.2.0",
    "@babel/preset-env": "^7.2.3",
    "babel-core": "7.0.0-bridge.0",
    "jest": "^23.6.0"
  }
}

this is .babelrc:

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "@babel/plugin-transform-modules-commonjs"
  ]
}

this is jest.config.js:

module.exports = {
    verbose: true,
    transform: {
        "^.+\\.jsx?$": "babel-jest"
    },
    bail: true,
    browser: true,
    cacheDirectory: '/tmp/jest',
    collectCoverage: false,
    roots: [
        '<rootDir>/../js',
        '<rootDir>/jest'
    ],
    moduleNameMapper: {
        '^(.*)/js/(.*)$': '<rootDir>/../js/$2'
    },
    testRegex: '(jest/spec/.*|(\\.|/)(test|spec))\\.js$',
    testPathIgnorePatterns: [
        '<rootDir>/node_modules'
    ],
    transformIgnorePatterns: [
        '/node_modules/'
    ]
};

So I've tried to look for similar cases around the web but in most cases the problems come from /node_modules or something missing in the jest config. But I can't find what's wrong in my case, would really appreciate any hints what can I try

up: someone suggested that I need to add babel-jest to my package.json but it's already in /node_modules - it is added with jest package

1 Answers

The problem surrounds the fact that you have no babel-loader setup so the project will blow up on import and export commands that do not get removed from the source code during compilation as babel has no idea how to handle that without babel-loader installed and configured.

For a quick example of how to get started with ES6 transpiling and module loading you can check out this example.

youtube.com/watch?v=X5wTsHRsbIA

Related