Sven Lauterbach
Sven Lauterbach

Reputation: 430

Using es modules with nodejs and mocha

I try to use mocha with nodejs es modules, but I receive the following error message when running "mocha":

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Projects\NodeJsDemo\index' imported from C:\Projects\NodeJsDemo\test\index.spec.js
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:391:11)
at moduleResolve (node:internal/modules/esm/resolve:893:10)
at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:1004:11)
at Loader.resolve (node:internal/modules/esm/loader:89:40)
at Loader.getModuleJob (node:internal/modules/esm/loader:242:28)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36)

I already checked the Mocha documentation, which states:

To enable this you don’t need to do anything special. Write your test file as an ES module. In Node.js this means either ending the file with a .mjs extension, or, if you want to use the regular .js extension, by adding "type": "module" to your package.json

Based on this description I thought it would be enough to update the package.json with the "type":"module" property. My project is quite simple:

My project looks like

  Project
  |__ test
      |__ index.spec.js
  |__ index.js
  |__ package.json

package.json

{
  "name": "nodejsdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "mocha": "^9.1.1"
  },
  "dependencies": {
    "chai": "^4.3.4"
  }
}

index.js

export function hello() {
    return "hello"
}

test/index.spec.js

import { expect } from 'chai';
import { hello } from '../index';

describe('hello', function () {
    it('should return "hello"', function () {

        const actual = hello();
        expect(actual).to.equal("hello");
    });
});

Software versions:

What do I have todo to get this simple test running?

Upvotes: 1

Views: 1765

Answers (1)

Sven Lauterbach
Sven Lauterbach

Reputation: 430

The answer was just one link away from the mocha documentation I posted. From the NodeJS documentation:

Relative specifiers like './startup.js' or '../config.mjs'. They refer to a path relative to the location of the importing file. The file extension is always necessary for these.

So in instead of

import { hello } from '../index';

It has to be

import { hello } from '../index.js';

Upvotes: 1

Related Questions