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

如何在Node.js测试文件中为函数正确使用middy中间件?

问题原因

Middy 封装后的 handler 遵循 Lambda 标准入参规范,仅支持3个参数:event(事件对象)、context(运行上下文)、callback(可选回调函数)。你调用时传入了6个参数,第四个参数getDnisConfig被 Middy 识别为回调函数执行,因此触发callback is not a function报错。

修改方案
  • 将额外需要传入的参数(getDnisConfig、toResponse等)统一挂载到context或者event对象中,不要直接作为 handler 的独立入参传递
  • 调用 Middy 封装后的 handler 时仅传入3个标准入参,async 场景下可以省略 callback 参数直接 await 拿返回值
  • 如果原始baseHandler的逻辑依赖多参数取值,同步调整为从context/event中读取对应参数
  • 如果getDnisConfig、toResponse是sinon生成的测试桩,直接挂载到context对象上即可,不影响stub的调用统计逻辑

修改后的测试代码示例:

const app = require('../../main/baseHandler');
// 构造context对象,挂载额外参数
const context = {
  getDnisConfig,
  toResponse
};
const handler = middy(app.baseHandler).use(validator(validatorSchema));
// 仅传标准的event和context两个参数,async场景无需传callback
const response = await handler(event, context);

同步调整baseHandler的参数取值逻辑:

exports.baseHandler = async (event, context) => {
  // 从context中取出挂载的参数
  const { getDnisConfig, toResponse } = context;
  // 原有业务逻辑无需改动
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:54:03