为何带钩子的Mocha无法在VS Code调试器中正常运行?
给Mocha单元测试添加全局beforeAll钩子后,通过npm run test能正常执行,但用VSCode的launch.json调试配置启动测试时抛出异常。
现有配置
package.json中的test脚本
"scripts": { "test": "mocha --file src/tests/mochaHooks.js --loader=ts-node/esm src/tests/**/*.test.ts", }
VSCode launch.json调试配置
"configurations": [{ "type": "node", "request": "launch", "name": "Mocha Tests", "program": "node_modules/mocha/bin/mocha.js", "args": [ "--file", "src/tests/mochaHooks.js", "--loader=ts-node/esm", "src/tests/**/*.test.ts", "--colors" ] }]
错误信息
/Users/username/.nvm/versions/node/v18.18.2/bin/node node_modules/mocha/bin/mocha.js --file src/tests/mochaHooks.js --loader=ts-node/esm src/tests/**/*.test.ts
(node:45105) ExperimentalWarning: Custom ESM Loaders is an experimental feature and might change at any time
(Usenode --trace-warnings ...to show where the warning was created)
warning:60ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has '.js' file extension and '/Users/markericson/Develop/sowrulesengine/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///Users/markericson/Develop/sowrulesengine/src/tests/mochaHooks.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
run.js:372
Process exited with code 1
报错的钩子代码
exports.mochaHooks = { beforeAll(done) { initialization() done() }, }
解决方案
方案1:将钩子文件转为ES模块格式
由于项目package.json中设置了"type": "module",所有.js文件默认被识别为ES模块,不能使用CommonJS的exports语法。修改mochaHooks.js为ESM导出方式:
export const mochaHooks = { beforeAll(done) { initialization() done() }, }
方案2:重命名钩子文件为.cjs后缀
将mochaHooks.js改名为mochaHooks.cjs,Node会自动将其识别为CommonJS模块,无需修改代码。同时同步更新两处配置中的文件路径:
修改后的package.json脚本:
"scripts": { "test": "mocha --file src/tests/mochaHooks.cjs --loader=ts-node/esm src/tests/**/*.test.ts", }
修改后的launch.json配置:
"configurations": [{ "type": "node", "request": "launch", "name": "Mocha Tests", "program": "node_modules/mocha/bin/mocha.js", "args": [ "--file", "src/tests/mochaHooks.cjs", "--loader=ts-node/esm", "src/tests/**/*.test.ts", "--colors" ] }]
内容的提问来源于stack exchange,提问作者Mark_Sagecy

