11

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

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Jack
  • 1,689
  • 1
  • 13
  • 20

2 Answers2

4

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

joshuanapoli
  • 2,509
  • 3
  • 25
  • 34
-2

I was not used jest, and I am not sure if this will solve, but I hope this can help you.

Node still doesn't support all syntax. If you really are looking a faster way to start develop, using source code with all features of Ecmascript2017, you need a module like @kawix/core https://www.npmjs.com/package/@kawix/core

How the README.md says, allows you to use all features including "imports" and "async/await" and also supports typescript, and other good features all without a LOT OF DEPENDENCIES. You can use directly with cli:

> npm install -g @kawix/core
> kwcore /path/to/fullsyntaxtsupport.js

Or if you want inclute programatically, create a file example main.js to import the fully syntax file

var kawix= require("@kawix/core")
kawix.KModule.injectImport()
kawix.KModule.import("/path/to/fullsyntaxtsupport.js").catch(function(e){
    console.error("Some error: ",e)
})
James Suárez
  • 327
  • 2
  • 5