Mocha测试对本地ES6模块具有“ ESM”支持

问题描述

Alex Gibson发表了很棒的帖子“ Testing native ES modules using Mocha and esm”。谢谢他。

我尝试在项目中使用具有本机ES模块支持的mocha,但遇到2个不同的错误

$ ./node_modules/mocha/bin/mocha --require esm './test/Util.test.js'

TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback was not specified.
    at exports.importModuleDynamicallyCallback (internal/process/esm_loader.js:41:9)
    at formattedImport (/.../node_modules/mocha/lib/esm-utils.js:6:23)
    at Object.exports.requireOrImport (/.../node_modules/mocha/lib/esm-utils.js:23:14)
    at Object.exports.loadFilesAsync (/.../node_modules/mocha/lib/esm-utils.js:33:34)
    at Mocha.loadFilesAsync (/.../node_modules/mocha/lib/mocha.js:427:19)
    ...
$ /usr/bin/node /.../node_modules/mocha/bin/mocha -r esm --ui bdd --reporter \ 
  /.../PHPStorm/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js \ 
  /.../test/Util.test.js

TypeError: Invalid host defined options
    at formattedImport (/.../node_modules/mocha/lib/esm-utils.js:6:23)
    at Object.exports.requireOrImport (/.../node_modules/mocha/lib/esm-utils.js:23:14)
    at Object.exports.loadFilesAsync (/.../node_modules/mocha/lib/esm-utils.js:33:34)
    at Mocha.loadFilesAsync (/.../node_modules/mocha/lib/mocha.js:427:19)
    ...

解决方法

更新:我认为该错误的原因是--require esm参数中的mocha选项与其他指示源是ES6模块的方法({{1 }}或*.mjs中的type选项)。我当前的测试具有package.json扩展名,并且在.mjs中没有"type": "module"的情况下也会发生相同的错误

老员工

我一直在寻找原因,这就是原因-我自己的package.json

package.json

来自nodejs.org的注释:

Node.js默认将JavaScript代码视为CommonJS模块。作者可以通过.mjs文件扩展名,package.json“类型”字段或--input-type标志,告诉Node.js将JavaScript代码视为ECMAScript模块。

只需从您的"type": "module" 中删除"type": "module",然后package.json就可以在mocha支持下运行测试,如Alex Gibson的帖子所述。

这是我的测试仓库,其中包含尝试使用的代码:flancer64/so_mocha_esm

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...