Skip to content Skip to sidebar Skip to footer

Is It Possible To Use Es6 Modules In Mocha Tests?

ES6, Windows 10 x64, Node.js 8.6.0, Mocha 3.5.3 Is it possible to use ES6 modules in Mocha tests? I have the problems with export and import keywords. /* eventEmitter.js */ /* Ev

Solution 1:

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 esm as an alternative to Mocha's built-in module support, but that package 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"
    ]
}

And this setup requires the following packages:

  • @babel/core
  • @babel/register
  • @babel/preset-env
  • regenerator-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.

Solution 2:

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

Solution 3:

Post a Comment for "Is It Possible To Use Es6 Modules In Mocha Tests?"