在 nodejs 和 mocha 中使用 es 模块

Using es modules with nodejs and mocha

我尝试将 mocha 与 nodejs es 模块一起使用,但是当 运行 "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)

我已经检查了 Mocha documentation,其中指出:

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

根据此描述,我认为用“type”:“module”属性 更新 package.json 就足够了。我的项目很简单:

我的项目看起来像

  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");
    });
});

软件版本:

我需要做什么才能获得这个简单的测试 运行?

答案与我发布的 mocha 文档仅相差 link。来自 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.

所以代替

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

必须

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