ecmascript-6jestjsbabel-jest

Does Jest support ES6 import/export?


If I use import/export from ES6 then all my Jest tests fail with error:

Unexpected reserved word

I convert my object under test to use old school IIFE syntax and suddenly my tests pass. Or, take an even simpler test case:

   var Validation = require('../src/components/validation/validation'); // PASS
   //import * as Validation from '../src/components/validation/validation' // FAIL

Same error. Obviously there's a problem with import/export here. It's not practical for me to rewrite my code using ES5 syntax just to make my test framework happy.

I have babel-jest. I tried various suggestions from GitHub issues. It is no go so far.

File package.json

 "scripts": {
    "start": "webpack-dev-server",
    "test": "jest"
  },
      "jest": {
        "testPathDirs": [
          "__tests__"
        ],
        "testPathIgnorePatterns": [
          "/node_modules/"
        ],
        "testFileExtensions": ["es6", "js"],
        "moduleFileExtensions": ["js", "json", "es6"]
      },

File babelrc

{
  "presets": ["es2015", "react"],
  "plugins": ["transform-decorators-legacy"]
}

Is there a fix for this?


Solution

  • [Dec 2023 UPDATE]

    Now you can support ES6 and ESM (ECMAScript modules) natively.

    It's a prerequisite to set "type": "module" to your package.json.

    Here are the steps:

    Step 1: Prevent Jest from trying to transform ESM code to CommonJS, updating your Jest config (package.json example below) with:

    "jest": {
        ...
        "transform": {}
    }
    
    

    Step 2: To be able to parse ES modules without an external transformer (e.g., babel), start Node with the --experimental-vm-modules flag. This can be done by changing how Jest is started by the npm "test" script (again inside package.json):

    "scripts": {
        "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
    }
    

    And that's it. :)

    You can even uninstall your transformer packages if you were using them just for the tests.


    [OUTDATED answer, just for historic purposes]

    From my answer to another question, this can be simpler:

    The only requirement is to configure your test environment to Babel, and add the ECMAScript 6 transform plugin:


    Step 1:

    Add your test environment to .babelrc in the root of your project:

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

    Step 2:

    Install the ECMAScript 6 transform plugin:

    npm install --save-dev @babel/plugin-transform-modules-commonjs
    

    And that's it. Jest will enable compilation from ECMAScript modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.