4

I use Node.js v14.17.0, Mocha 9.0.2. My project is a bare-bone project configured to use ES6 js module made for the understanding of this issue.

{
  "name": "mocha-tlp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC",
  "type": "module"
}

With the test case (test/foo.js):

import assert from 'assert/strict';

describe('MyObject', function () {
    describe('#myFunction()', function () {
        it('should work', function () {
            assert(true, "All good");
        });
    });
});

I get the following error :

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\xxxxxxxxxxxxxx\test\foo.js
require() of ES modules is not supported.
require() of C:\xxxxxxxxxxxxxx\test\foo.js from C:\xxxxxxxxxxxxxx\node_modules\mocha\lib\esm-utils.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename foo.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\projects\svelte\dgb-app\package.json.

It does not seems to be a issue that esm and mocha --require esm could solve because both Node.js and Mocha supports ESM for those version.

How can I use Nodejs Assert with Mocha when ESM project ?

Gabriel Glenn
  • 1,174
  • 1
  • 13
  • 30
  • Does this answer your question? [Error: require() of ES modules is not supported when importing node-fetch](https://stackoverflow.com/questions/69041454/error-require-of-es-modules-is-not-supported-when-importing-node-fetch) – deltree Feb 01 '22 at 20:02

1 Answers1

0

Since assert is a built in node module, you may use:

import assert from 'node:assert/strict'
Dshiz
  • 3,099
  • 3
  • 26
  • 53
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 05 '22 at 17:50