如何为supertest/chai-http的Node服务器添加--experimental-specifier-resolution参数
问题描述
开发Node.js Express ES模块应用时,使用Mocha+chai-http编写测试,项目启动依赖--experimental-specifier-resolution=node参数支持目录导入,但运行测试时抛出错误:
Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/home/konrad/Projects/MW/src/routes' is not supported resolving ES modules imported from /home/konrad/Projects/MW/src/index.js at new NodeError (node:internal/errors:372:5) at finalizeResolution (node:internal/modules/esm/resolve:433:17) at moduleResolve (node:internal/modules/esm/resolve:1009:10) at defaultResolve (node:internal/modules/esm/resolve:1218:11) at ESMLoader.resolve (node:internal/modules/esm/loader:580:30) at ESMLoader.getModuleJob (node:internal/modules/esm/loader:294:18) at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40) at link (node:internal/modules/esm/module_job:78:36)
测试代码示例:
import chai from "chai"; import chaiHttp from "chai-http"; import app from "../src/index.js"; chai.use(chaiHttp); describe("Test one", () => { describe("should be happy", () => { it("something", (done) => { chai .request(app) .get("/") .end((err, res) => { console.log("ERR", err); console.log("RES", res); done(); }); }); }); });
解决方案
不需要自定义chai-http/supertest的启动流程,直接给Mocha传递Node.js的实验性参数即可,以下是两种常用方式:
1. 启动命令直接传递参数
运行Mocha时,通过--node-option(简写-n)参数将experimental-specifier-resolution=node传给Node进程:
mocha --node-option experimental-specifier-resolution=node
如果是在package.json的scripts中配置测试命令:
{ "scripts": { "test": "mocha --node-option experimental-specifier-resolution=node" } }
2. 通过Mocha配置文件自动加载参数
创建.mocharc.json配置文件,添加nodeOption配置项:
{ "nodeOption": ["experimental-specifier-resolution=node"] }
后续直接运行mocha命令,Mocha会自动读取该配置,为Node进程注入所需参数。
原理说明
chai-http是直接导入你的Express应用模块,而模块的解析规则由Node.js进程控制。只要Mocha启动时带上--experimental-specifier-resolution=node,整个测试环境的Node进程就会启用目录导入支持,导入app模块时就不会触发目录导入不支持的错误。
内容的提问来源于stack exchange,提问作者senp_linux
相关产品推荐
相关产品推荐

