Search code examples
aws-lambdamockinges6-promisesinonaws-sdk-mock

Mock Lambda.invoke wrapped but not being called


I'm having an issue while trying to mock lambda.invoke which I'm calling from within another lambda function.

  • The function is wrapped (I can't use sinon after, it will tell me it's already wrapped).
  • The test keeps calling the lambda function on AWS instead of calling the mock.
  • It does the same if I use sinon instead of aws-sdk-mock.

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);
  });
});

and my lambda function is:

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});
    });
  });
};

EDIT: So the issue I had was because I had my lambda initialisation (const lambda = new AWS.Lambda({})) outside the handler instead on inside. Thanks to stijndepestel's answer.


Solution

  • It is not entirely clear from the code you have shared, but presumably, you have a reference to lambda in your handler.js before you have wrapped the function in your test. Could you add the const lambda = new AWS.Lamda({}) line inside your handler function instead of outside of it?