23

I'm trying to test a file which needs to import an es6 module like this:

https://repl.it/HG9t/0

It seems I'm missing some configurations to make it work properly.

If you can achieve this with another unit testing framework easily, I'm interested too.

Thank you in advance for your help.

Alphapage
  • 851
  • 1
  • 6
  • 28

2 Answers2

11
  1. Install required dependencies:

yarn add --dev babel-jest @babel/core @babel/preset-env

or

npm install --save-dev babel-jest @babel/core @babel/preset-env

  1. Create babel.config.js in your main folder and paste it there:
// babel.config.js
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};
  1. Make sure all your jest settings in package.json and jest.config.js are set to default.
Ilyich
  • 3,530
  • 1
  • 29
  • 23
  • I got "Error while loading config - You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously." – Raine Revere May 09 '21 at 16:14
10

As node does not support modules you have to compile your files using Babel. Have a look at the docs on how to configure Jest and Babel

apnerve
  • 4,580
  • 5
  • 28
  • 44
Andreas Köberle
  • 98,250
  • 56
  • 262
  • 287
  • 11
    Node has been supporting modules with the `--experimental-modules` flag since v8.5. – Dan Dascalescu Aug 16 '18 at 01:22
  • 1
    Even without the .mjs extension? – Biel Simon Aug 23 '18 at 18:40
  • 5
    @BielSimon Yes, without the mjs extension. You need `"type": "module"` in your package.json and the flag mentioned by Dan. – Chris Magnuson Jun 10 '19 at 17:54
  • 2
    `"type": "module"` will only work from node v12 onwards https://nodejs.org/docs/latest-v12.x/api/esm.html but you can use `node -r esm` – velop Sep 05 '19 at 11:45
  • You don't even need `"type":"module"` at all (unless you do things the official Node way). If you just use `-r esm` ... with a normal library (eg. Node itself, or Mocha) that supports it, ES6 modules "just work". – machineghost Sep 16 '19 at 23:52
  • I'm getting `ReferenceError: module is not defined` when I put "type": "module" in my package.json file – roadev Feb 26 '21 at 01:29