How to Test AWS Lambda Functions Locally
You can test
AWS Lambda functions locally using the AWS SAM CLI, which simulates the Lambda runtime on your machine. This lets you run, debug, and invoke your Lambda code without deploying it to the cloud.Syntax
To test a Lambda function locally with AWS SAM CLI, use the command sam local invoke. This runs your Lambda handler code in a local Docker container that mimics the AWS Lambda environment.
Basic syntax:
sam local invoke [FunctionLogicalID] -e event.json- invokes the Lambda function with an event payload.sam local start-api- starts a local API Gateway to test Lambda functions triggered by HTTP requests.
bash
sam local invoke MyFunction -e event.json
Example
This example shows how to test a simple Lambda function locally using AWS SAM CLI. The Lambda function returns a greeting message.
plaintext
/* app.js */ exports.lambdaHandler = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: "Hello from Lambda!" }) }; }; /* template.yaml */ AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: HelloFunction: Type: AWS::Serverless::Function Properties: Handler: app.lambdaHandler Runtime: nodejs18.x /* event.json */ {}
Example
bash
sam build sam local invoke HelloFunction -e event.json
Output
{
"statusCode": 200,
"body": "{\"message\":\"Hello from Lambda!\"}"
}
Common Pitfalls
Common mistakes when testing Lambda locally include:
- Not having Docker installed or running, since
sam localuses Docker containers. - Using an event file that does not match the expected input format of your Lambda function.
- Forgetting to build the project with
sam buildbefore invoking. - Not setting environment variables locally that your Lambda depends on.
Always check Docker is running and your event JSON matches your function's input.
bash
/* Wrong: invoking without Docker running */ sam local invoke HelloFunction -e event.json /* Right: start Docker first, then build and invoke */ docker start sam build sam local invoke HelloFunction -e event.json
Quick Reference
Tips for testing Lambda locally:
- Install Docker and AWS SAM CLI before testing.
- Use
sam buildto prepare your code. - Use
sam local invokewith an event file to simulate Lambda invocation. - Use
sam local start-apito test HTTP-triggered Lambdas. - Check logs and errors in the terminal for debugging.
Key Takeaways
Use AWS SAM CLI with Docker to run Lambda functions locally.
Always build your Lambda project with 'sam build' before invoking locally.
Provide a proper event JSON file to simulate Lambda input.
Ensure Docker is installed and running before local testing.
Use 'sam local start-api' to test Lambda functions triggered by HTTP requests.