Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

babel-jest with ES6 modules

I'm happily using node 8.6 with the experimental ES6 modules option (--experimental-modules) turned on. This allows me to perfectly write plain ES2015 code for node without the need of babel.

The problem is when I try to create some tests with jest, it fails complaining about a syntax error: "Unexpected token import".

The .babelrc configuration is the following:

{
  "env": {
    "test": {
      "presets": [
        ["env", {
          "targets": {
            "node": "8.6"
          }
        }]
      ]
    }
  }
}

My jest.config.js is as follows:

module.exports = {
  testMatch: ['/tests/**/*.js', '**/?(*.)test.js'],
}

The error thrown:

    /app/tests/integration/controller/data-provider/Credentials/CredentialsList.action.test.js:2
    import { Credentials, AdWordsCredentials } from '../../../../../imports/models/data-provider/Credentials.mjs';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
          at Generator.next (<anonymous>)
          at Promise (<anonymous>)

Relevant packages:

  • babel-core@^6.26.0
  • jest@^21.2.1
  • babel-jest@^21.2.0
  • babel-preset-env@^1.6.0

Any help will be appreciated. Thanks :)

UPDATE: I've tried calling jest without babel, with the following command, without any change: node --experimental-modules node_modules/.bin/jest

like image 662
Jack Avatar asked Oct 08 '17 22:10

Jack


1 Answers

Jest has a custom implementation of require to help with mocking. Unfortunately, this makes jest incompatible with node --experimental-modules. Babel is probably the best way to use ES6 modules with jest. See https://github.com/facebook/jest/issues/4842

like image 103
joshuanapoli Avatar answered Nov 13 '22 07:11

joshuanapoli