You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express路由单元测试报错:Router.use()需中间件却获undefined

问题排查与解决

一、先解决Router.use() requires a middleware function but got a undefined错误

这个错误的核心是**healthController未被正确导入**,导致healthRouter的get方法传入了undefined,进而引发路由注册失败:

  • 检查src/controllers/health/index.js的导出方式:
    如果控制器是默认导出(如export default healthController),那routes/health/index.js里的import { healthController }会得到undefined,需要改成import healthController from '../../controllers/health/index.js';
    如果是命名导出,确保写法是export const healthController = (req, res) => { ... },导入时的解构语法才有效。
  • 验证文件路径:确认routes/health/index.js中导入控制器的路径../../controllers/health/index.js是否正确,避免拼写或层级错误。

二、解决测试中router为undefined的问题

1. 检查导入路径正确性

测试文件中导入router的路径是../../../src/routes/index.js,需确认测试文件的实际位置:

  • 假设测试文件放在tests/routes/index.test.js,正确路径应为../../src/routes/index.js(少一层../);
  • 路径错误会导致导入空值,直接引发router为undefined。

2. 适配测试环境的模块系统

如果项目使用ES模块(package.json中配置了"type": "module"),但测试框架(如Jest)默认使用CommonJS,需调整配置:

  • 在jest.config.js中添加:
    export default {
      transform: {},
      extensionsToTreatAsEsm: ['.js']
    }
    
  • 或在package.json的scripts中修改测试命令为:"test": "NODE_OPTIONS=--experimental-vm-modules jest",强制Jest使用ES模块解析。

三、修正测试预期值错误

测试中actualNumberRoutes设为2,但实际仅注册了/health这1个路由,需将其改为1,否则测试通过后仍会断言失败:

const actualNumberRoutes = 1

内容的提问来源于stack exchange,提问作者beesknees

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:50:39