Testing AWS Lambda Functions Locally

Testing AWS Lambda Functions Locally

Deploying to AWS to test every Lambda change is slow, expensive, and gives you no useful debugging information when things break. The deploy-test-iterate cycle on Lambda is 3–5 minutes per change. Local testing collapses this to seconds.

This guide covers the full local Lambda testing strategy: unit tests for function logic, integration tests against real dependencies, and end-to-end tests using the AWS SAM local runtime.

The Testing Pyramid for Lambda

Lambda functions typically do three things: receive an event, call downstream services, return a result. Each layer has a different test approach:

             ┌─────────────────┐
             │  E2E / Deployed │  Slow, expensive — minimal coverage
             ├─────────────────┤
             │ SAM Local / CDK │  Real runtime, mocked services
             ├─────────────────┤
             │  Unit (Jest)    │  Fast, isolated — most coverage
             └─────────────────┘

Write most of your tests at the unit level. Use SAM local for integration tests that need the Lambda runtime behavior (cold starts, environment variables, IAM context). Use deployed tests sparingly, only for smoke tests after deployment.

Unit Testing Lambda Functions

The Lambda handler is just a function. Test it like any other function:

// handler.js
const { DynamoDBClient, GetItemCommand } = require('@aws-sdk/client-dynamodb');

const client = new DynamoDBClient({});

exports.handler = async (event) => {
  const userId = event.pathParameters?.userId;
  
  if (!userId) {
    return {
      statusCode: 400,
      body: JSON.stringify({ error: 'Missing userId parameter' }),
    };
  }
  
  const result = await client.send(new GetItemCommand({
    TableName: process.env.USERS_TABLE,
    Key: { userId: { S: userId } },
  }));
  
  if (!result.Item) {
    return {
      statusCode: 404,
      body: JSON.stringify({ error: 'User not found' }),
    };
  }
  
  return {
    statusCode: 200,
    body: JSON.stringify({ userId: result.Item.userId.S, email: result.Item.email.S }),
  };
};
// handler.test.js
const { handler } = require('./handler');
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { mockClient } = require('aws-sdk-client-mock');

const ddbMock = mockClient(DynamoDBClient);

describe('Lambda handler', () => {
  beforeEach(() => {
    ddbMock.reset();
    process.env.USERS_TABLE = 'test-users-table';
  });
  
  test('returns 400 when userId is missing', async () => {
    const event = { pathParameters: null };
    const result = await handler(event);
    
    expect(result.statusCode).toBe(400);
    expect(JSON.parse(result.body).error).toBe('Missing userId parameter');
  });
  
  test('returns 404 when user not found', async () => {
    ddbMock.on(GetItemCommand).resolves({ Item: undefined });
    
    const event = { pathParameters: { userId: 'nonexistent' } };
    const result = await handler(event);
    
    expect(result.statusCode).toBe(404);
  });
  
  test('returns user data when found', async () => {
    ddbMock.on(GetItemCommand).resolves({
      Item: {
        userId: { S: 'user-123' },
        email: { S: 'test@example.com' },
      },
    });
    
    const event = { pathParameters: { userId: 'user-123' } };
    const result = await handler(event);
    
    expect(result.statusCode).toBe(200);
    
    const body = JSON.parse(result.body);
    expect(body.userId).toBe('user-123');
    expect(body.email).toBe('test@example.com');
  });
  
  test('propagates DynamoDB errors', async () => {
    ddbMock.on(GetItemCommand).rejects(new Error('DynamoDB unavailable'));
    
    const event = { pathParameters: { userId: 'user-123' } };
    
    await expect(handler(event)).rejects.toThrow('DynamoDB unavailable');
  });
});

Using aws-sdk-client-mock

The aws-sdk-client-mock library (v3 SDK) is the right tool for mocking AWS SDK calls in unit tests. Avoid manual mocking with jest.mock — it's brittle and breaks when AWS SDK internals change.

npm install --save-dev aws-sdk-client-mock @aws-sdk/client-dynamodb

Key patterns:

  • mockClient(DynamoDBClient) creates a mock for an SDK client class
  • .on(CommandClass) matches calls to a specific command
  • .resolves(value) returns a resolved promise
  • .rejects(error) returns a rejected promise
  • .callsFakeOnce(fn) for dynamic responses
  • ddbMock.reset() in beforeEach prevents test pollution

Testing Different Event Sources

Lambda functions are triggered by different event sources. Each has a specific event shape. Test with realistic events:

API Gateway Events

// Realistic API Gateway v2 (HTTP API) event
const apiGatewayEvent = {
  version: '2.0',
  routeKey: 'POST /users',
  rawPath: '/users',
  requestContext: {
    accountId: '123456789',
    apiId: 'abc123',
    http: {
      method: 'POST',
      path: '/users',
      sourceIp: '1.2.3.4',
    },
    requestId: 'req-123',
    stage: '$default',
    time: '12/Mar/2024:19:03:58 +0000',
  },
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer token123',
  },
  body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' }),
  isBase64Encoded: false,
};

SQS Events

const sqsEvent = {
  Records: [
    {
      messageId: 'msg-001',
      receiptHandle: 'receipt-001',
      body: JSON.stringify({ orderId: 'order-123', action: 'process' }),
      attributes: {
        ApproximateReceiveCount: '1',
        SentTimestamp: '1680000000000',
      },
      messageAttributes: {},
      md5OfBody: 'abc123',
      eventSource: 'aws:sqs',
      eventSourceARN: 'arn:aws:sqs:us-east-1:123456789:my-queue',
      awsRegion: 'us-east-1',
    },
  ],
};

test('processes SQS messages correctly', async () => {
  const result = await handler(sqsEvent);
  
  // For SQS, Lambda should return batchItemFailures for partial failures
  expect(result).toEqual({ batchItemFailures: [] });
});

test('reports failed messages in batchItemFailures', async () => {
  // Mock a failure for the second message
  const twoMessageEvent = {
    Records: [
      { ...sqsEvent.Records[0], messageId: 'msg-001' },
      { ...sqsEvent.Records[0], messageId: 'msg-002', body: JSON.stringify({ invalid: true }) },
    ],
  };
  
  const result = await handler(twoMessageEvent);
  
  // First message succeeded, second failed
  expect(result.batchItemFailures).toHaveLength(1);
  expect(result.batchItemFailures[0].itemIdentifier).toBe('msg-002');
});

Testing with SAM Local

AWS SAM Local runs your Lambda in a Docker container with the actual Lambda runtime. Use it when you need to test environment variables, IAM context, or Lambda runtime behavior.

Setup

# Install SAM CLI
brew tap aws/tap
brew install aws-sam-cli

# Your template.yaml
cat > template.yaml << 'EOF'
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: nodejs20.x
    Environment:
      Variables:
        USERS_TABLE: test-users-table
        AWS_REGION: us-east-1

Resources:
  GetUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.handler
      CodeUri: ./src
      Events:
        GetUser:
          Type: HttpApi
          Properties:
            Path: /users/{userId}
            Method: get
EOF

Invoking Functions Locally

# Direct invocation with a test event
sam local invoke GetUserFunction --event events/get-user.json

# Start API locally
sam local start-api --port 3001

# Then test against it
curl http://localhost:3001/users/user-123

Automated SAM Local Tests

// integration/sam-local.test.js
const fetch = require('node-fetch');
const { execSync, spawn } = require('child_process');

describe('SAM Local integration', () => {
  let samProcess;
  const PORT = 3001;
  
  beforeAll(async () => {
    // Start SAM local API
    samProcess = spawn('sam', ['local', 'start-api', '--port', PORT.toString()], {
      stdio: 'pipe',
    });
    
    // Wait for startup
    await new Promise((resolve) => {
      samProcess.stdout.on('data', (data) => {
        if (data.toString().includes('Running on')) resolve();
      });
    });
  }, 60000); // SAM startup can be slow (Docker pull)
  
  afterAll(() => samProcess.kill());
  
  test('GET /users/:id returns user data', async () => {
    const response = await fetch(`http://localhost:${PORT}/users/test-user`);
    expect(response.status).toBe(200);
    
    const data = await response.json();
    expect(data.userId).toBe('test-user');
  });
  
  test('Lambda cold start occurs on first request', async () => {
    const start = Date.now();
    await fetch(`http://localhost:${PORT}/users/user-1`);
    const coldStartTime = Date.now() - start;
    
    const warmStart = Date.now();
    await fetch(`http://localhost:${PORT}/users/user-2`);
    const warmStartTime = Date.now() - warmStart;
    
    // Cold start should be significantly slower
    console.log(`Cold start: ${coldStartTime}ms, Warm start: ${warmStartTime}ms`);
    expect(coldStartTime).toBeGreaterThan(warmStartTime);
  });
});

Environment Variable Testing

Lambda behavior often changes based on environment variables. Test this:

describe('environment-dependent behavior', () => {
  test('uses correct table name from environment', async () => {
    process.env.USERS_TABLE = 'prod-users';
    
    const capturingMock = ddbMock.on(GetItemCommand).resolves({ Item: null });
    
    await handler({ pathParameters: { userId: 'u1' } });
    
    const call = capturingMock.call(0);
    expect(call.args[0].input.TableName).toBe('prod-users');
    
    delete process.env.USERS_TABLE;
  });
  
  test('throws when required env var is missing', async () => {
    delete process.env.USERS_TABLE;
    
    await expect(handler({ pathParameters: { userId: 'u1' } }))
      .rejects.toThrow(/USERS_TABLE/);
  });
});

Testing Timeouts

Lambda has a maximum timeout. Test what happens when your function approaches it:

test('function completes within timeout budget', async () => {
  const LAMBDA_TIMEOUT_MS = 3000; // Your function's configured timeout
  const SAFETY_MARGIN_MS = 500;
  
  const start = Date.now();
  await handler(validEvent);
  const elapsed = Date.now() - start;
  
  expect(elapsed).toBeLessThan(LAMBDA_TIMEOUT_MS - SAFETY_MARGIN_MS);
});

Continuous Monitoring with HelpMeTest

Unit tests and SAM local catch development bugs. HelpMeTest monitors your deployed Lambda endpoints continuously:

*** Test Cases ***
Lambda API Endpoint Health Check
    [Documentation]    Verify deployed Lambda returns expected responses
    ${response}=    GET    https://api.yourapp.com/users/health-check-user
    Status Code Should Be    ${response}    200
    ${body}=    Parse JSON    ${response.body}
    Should Be Equal    ${body}[userId]    health-check-user
    Response Time Should Be Under    500ms

Run this every 5 minutes. Lambda cold starts after inactivity can push response times over your SLA. Continuous monitoring catches cold start regressions after deployments before users notice.

Common Lambda Testing Mistakes

Mocking the entire AWS SDK. Instead, use aws-sdk-client-mock which respects the SDK's serialization logic. Manual mocking with jest.mock('@aws-sdk/client-dynamodb') skips SDK validation and misses type errors.

Not testing the event shape. Real API Gateway events have dozens of fields your handler may rely on. Test with realistic events that match production, not minimal objects.

Skipping error path testing. Lambda errors manifest differently depending on the invocation type: synchronous (API Gateway) returns an error response; asynchronous (SQS) retries; stream-based (Kinesis) stalls. Test error handling for your specific invocation type.

Hardcoding region in tests. process.env.AWS_REGION must be set before testing. Lambda sets it automatically in production; your tests must set it explicitly.

Not testing concurrency. Lambda scales by running multiple instances concurrently. If your function has initialization code that runs once per instance (database connection setup), test that it works correctly under concurrent invocations.

Read more

Start now free