Lambda.invoke and local testing

I have a specific use-case where one lambda function needs to call another and await the response (I know about sns and async lambdas, but this is a design requirement).

It seems that local testing will always use a PUBLISHED lambda function, and not the local. Is there anyway that my local tests can use the local handlers the dev is working on?

lambda.invoke({
// TODO: this actually invokes the AWS live version. Not sure how to test local with lambda invoke.
FunctionName: ‘child_func_test’,
Payload: ‘{}’
}, function(error, data) {
cb(null, data)
});

I’ve looked at this topic but the answers don’t fit: Sls lambda to invoke *local* version of lambda, not aws hosted

Any advice?

1 Like

Create a module, let’s call it invokeLambda that looks a bit like this (simplified):

module.exports = (options, callback) => lambda.invoke(options, callback);

Then another module, say invokeLocal that does something like:

module.exports = (options, callback) => require(`./path/to/${options.FunctionName}`)(options.Payload, callback);

Note that this assumes a 1-to-1 relationship between function name and file name, this might not be the case but hopefully you can use some method to determine the filename from the function name (?) Otherwise you might have to fall back to a static map, or perhaps you could read serverless.yml and get it from there.

Then you can inject whichever one of these is relevant, based on some test that you can use to determine where the code is running. It could be as simple as something like:

invoke = stageVariables.stage === 'local' ? require('./path/to/invokeLocal') : require('./path/to/invokeLambda');

Then, you can use it, and whichever method is defined for the environment, will be used:

invoke({ FunctionName: 'test', ... });

HTH