Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use mjs module in mocha? #4313

Closed
wnghdcjfe opened this issue Jun 5, 2020 · 4 comments
Closed

How to use mjs module in mocha? #4313

wnghdcjfe opened this issue Jun 5, 2020 · 4 comments
Labels
duplicate been there, done that, got the t-shirt... type: question support question

Comments

@wnghdcjfe
Copy link
Contributor

I try to use mocha like this for this reference
https://mochajs.org/#nodejs-native-esm-support

main.mjs

import {add} from './add.mjs';
import assert from 'assert';

it('should add to numbers from an es module', () => {
  assert.equal(add(3, 5), 8);
});

add.mjs

export function add(a, b){
    return a + b; 
} 

command

mocha main.js --experimental-modules
mocha main.js --extension mjs

But both of them is not working

I also found the npm link
https://www.npmjs.com/package/mjs-mocha
But Can't Mocha just alone do that?

version

  • mocha : v7.2.0
  • node : v10.15.1
@wnghdcjfe wnghdcjfe added the type: question support question label Jun 5, 2020
@juergba
Copy link
Member

juergba commented Jun 5, 2020

Mocha supports ES modules only from Node.js v12.11.0 and above. To enable this in versions smaller than 13.2.0, you need to add --experimental-modules when running Mocha. From version 13.2.0 of Node.js, you can use ES modules without any flags.

@juergba
Copy link
Member

juergba commented Jun 6, 2020

duplicate of #4297

@juergba juergba closed this as completed Jun 6, 2020
@juergba juergba added the duplicate been there, done that, got the t-shirt... label Jun 6, 2020
@wnghdcjfe
Copy link
Contributor Author

Thanks a lot @juergba. Have nice a day

@meszaros-lajos-gyorgy
Copy link

For anyone googleing why --watch is not working with mjs files, the docs state, that this is a known limitation: https://github.com/mochajs/mocha/blob/master/docs/index.md#current-limitations

Watch mode does not support ES Module test files

One possible workaround is to use nodemon and it's --exec flag:

"scripts": {
  "unit": "mocha --experimental-modules --no-warnings test/**/*.spec.mjs",
  "unit:watch": "nodemon --exec \"npm run unit\" --watch test/**/*.spec.mjs",
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate been there, done that, got the t-shirt... type: question support question
Projects
None yet
Development

No branches or pull requests

3 participants