Is it possible to use ES6 modules in Mocha tests?

In my case run with:

basic comand:

npx mocha --require esm test_path/

package.json

"scripts": {
    // ...
    "test": "npx mocha --require esm --reporter spec test_path/"
}

Runing

npm test

Mocha has support for ESM from version 7.1.0 onward (release: Feb. 26, 2020).

This requires Node 12.11.0 or higher, and is subject to the current restrictions/limitations of using modules in Node:

  • Either you must use .mjs file extensions for source files that use ES modules, or you must have "type": "module" in your package.json
  • You can't use named imports when importing from CommonJS modules
  • Local import statements have to explicitly include the .js file extension

And so on.

Updated answer

I had previously recommended using the esm package as an alternative to Mocha's built-in module support, but it is no longer being mantained, can't handle newer syntactical constructs like ?., and seems to possibly not work at all with newer versions of Mocha.

However, @babel/register seems to work well for this:

mocha -r @babel/register -r regenerator-runtime/runtime

I'm using this with this preset (in .babelrc):

{
    "presets": [
        "@babel/preset-env"
    ]
}

This setup requires the following packages:

  • @babel/core
  • @babel/register
  • @babel/preset-env
  • regenerator-runtime

You can also specify these in your .mocharc.js file instead of on the command line:

module.exports = {
    require: [
        '@babel/register',
        'regenerator-runtime/runtime',
    ],
};

My personal experience as of yet is that trying to take advantage of Mocha's new, inherent ESM support is still a considerable burden, but using this approach is quite seamless.

Previous answer

Another option is to use the esm package, which is not subject to the above limitations:

mocha -r esm

My personal experience as of yet is that trying to take advantage of Mocha's new, inherent ESM support is still a considerable burden, but using the esm package is quite seamless.