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

使用Jest测试Middy包装的AWS Lambda Handler遇callback非函数错误

问题解决:Middy包装Lambda后测试callback报错callback is not a function

核心原因

Middy包装async类型的Lambda handler时,会遵循Lambda的async函数规范——优先使用函数返回值,而非callback。包装后的handler不会将你传入的callback参数直接传递给原始的ingest函数,因此触发callback is not a function错误。

解决方案

方案1:符合Lambda async规范,改用return返回响应(推荐)

Lambda官方建议async函数直接return响应,无需使用callback,Middy对这种模式的支持更完善。

修改业务代码:

async function ingest(event, _) {
    const response = someFunc(); // 修正变量引用,确保响应变量已定义
    return response;
};

修改测试代码,断言返回值:

it('should return expected response', async () => {
    const event = { message: 'some data'};
    const expectedResponse = { statusCode: 200, message: "test" };
    someFunc = jest.fn().mockReturnValue(expectedResponse);

    const context = {
        awsRequestId: 'test-request-id',
        functionName: 'test-function-name',
        getRemainingTimeInMillis: () => 5000,
    };

    const result = await handler(event, context);
    expect(result).toEqual(expectedResponse);
});

方案2:直接测试原始handler函数(兼容旧代码)

如果必须保留callback模式,且无需测试Middy的包装逻辑,可以直接调用未被Middy包装的ingest函数:

修改测试代码:

it('should call the callback', async () => {
    const event = { message: 'some data'};
    const expectedResponse = { statusCode: 200, message: "test" };
    someFunc = jest.fn().mockReturnValue(expectedResponse);

    const context = {
        awsRequestId: 'test-request-id',
        functionName: 'test-function-name',
        getRemainingTimeInMillis: () => 5000,
    };

    const callback = jest.fn();

    await ingest(event, context, callback); // 直接调用原始的ingest函数
    expect(callback).toHaveBeenCalledWith(null, expectedResponse);
});

额外注意点

检查业务代码中的response变量是否已定义——原代码中callback(null, response);的response未赋值,属于笔误,应改为callback(null, a);或者直接使用someFunc()的返回值,否则会引发新的未定义变量错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:15:24