模拟 Lambda.invoke 已包装但未被调用

Mock Lambda.invoke wrapped but not being called

我在尝试模拟从另一个 lambda 函数中调用的 lambda.invoke 时遇到问题。

test.js

const { handler1 } = require('../handler');
const sinon = require('sinon');
const AWSMock = require('aws-sdk-mock');

describe('invoke', () => {
  beforeEach(() => {
    invokeMock = jest.fn();
    AWSMock.mock('Lambda', 'invoke', invokeMock);
    // const mLambda = { invoke: sinon.stub().returnsThis(), promise: sinon.stub() };
    // sinon.stub(AWS, 'Lambda').callsFake(() => mLambda);
  });

  afterEach(() => {
    AWSMock.restore();
    sinon.restore();
  });

  test('test1', async () => {
    const event = { test: 'ok'};
    const handler = await handler1(event);
    expect(handler.statusCode).toBe(204);
  });
});

我的 lambda 函数是:

handler.js

const AWS = require('aws-sdk');

module.exports.handler1 = (event) => {
  // The initialisation bellow has to be in the handler not outside.
  const lambda = new AWS.Lambda({
    region: 'us-west-2' //change to your region
  });
  let params = {
    InvocationType: 'Event',
    LogType: 'Tail',
    FunctionName: 'handler2', // the lambda function we are going to invoke
    Payload: JSON.stringify(event)
  };
  return new Promise((resolve, reject) => {
    lambda.invoke(params, function(error, data) {
      if(error) return reject(error);
      const payload = JSON.parse(data.Payload);
      if(!payload.success){
        return resolve({ statusCode: 400});
      }
      return resolve({ statusCode: 204});
    });
  });
};

编辑:所以我遇到的问题是因为我在处理程序外部而不是内部进行了 lambda 初始化 (const lambda = new AWS.Lambda({}))。感谢 stijndepestel 的回答。

从您共享的代码中看不完全清楚,但据推测,在将函数包装到测试中之前,您在 handler.js 中引用了 lambda。您可以在处理函数内部而不是外部添加 const lambda = new AWS.Lamda({}) 行吗?