Testing AWS Lambda Functions Locally with SAM and LocalStack

Testing AWS Lambda Functions Locally with SAM and LocalStack

Testing Lambda functions used to mean deploying to AWS, watching CloudWatch logs, and hoping you guessed right. AWS SAM CLI and LocalStack changed that. You can now run your entire serverless stack locally, including DynamoDB, S3, SQS, and API Gateway, with near-zero latency feedback loops.

This guide covers setting up a real local testing environment, writing unit tests, and running integration tests against emulated AWS services.

Prerequisites

You need:

  • AWS SAM CLI: brew install aws-sam-cli
  • Docker (LocalStack runs in a container)
  • LocalStack: pip install localstack or brew install localstack
  • AWS CLI configured (even with dummy credentials for local use)

Set dummy credentials for LocalStack so the SDK doesn't reject them:

export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
export AWS_DEFAULT_REGION=us-east-1

Project Structure

A typical SAM project looks like this:

my-service/
├── template.yaml          # SAM template
├── src/
│   ├── handlers/
│   │   ├── create-order.js
│   │   └── process-payment.js
│   └── lib/
│       └── dynamodb-client.js
├── tests/
│   ├── unit/
│   │   └── create-order.test.js
│   └── integration/
│       └── order-flow.test.js
└── events/
    └── create-order-event.json

The template.yaml defines your functions and the resources they need:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Runtime: nodejs20.x
    Environment:
      Variables:
        ORDERS_TABLE: !Ref OrdersTable
        AWS_ENDPOINT_URL: ""

Resources:
  CreateOrderFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/create-order.handler
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref OrdersTable
      Events:
        Api:
          Type: Api
          Properties:
            Path: /orders
            Method: post

  OrdersTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: orders
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: orderId
          AttributeType: S
      KeySchema:
        - AttributeName: orderId
          KeyType: HASH

Writing Unit Tests

Unit tests should isolate the Lambda handler from AWS SDK calls. Use Jest with manual mocks.

// src/handlers/create-order.js
const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
const { marshall } = require('@aws-sdk/util-dynamodb');
const { randomUUID } = require('crypto');

const client = new DynamoDBClient({
  endpoint: process.env.AWS_ENDPOINT_URL || undefined,
});

exports.handler = async (event) => {
  const body = JSON.parse(event.body);
  
  if (!body.productId || !body.quantity) {
    return {
      statusCode: 400,
      body: JSON.stringify({ error: 'productId and quantity are required' }),
    };
  }

  const order = {
    orderId: randomUUID(),
    productId: body.productId,
    quantity: body.quantity,
    status: 'pending',
    createdAt: new Date().toISOString(),
  };

  await client.send(new PutItemCommand({
    TableName: process.env.ORDERS_TABLE,
    Item: marshall(order),
  }));

  return {
    statusCode: 201,
    body: JSON.stringify(order),
  };
};

Unit tests mock the DynamoDB client entirely:

// tests/unit/create-order.test.js
const { mockClient } = require('aws-sdk-client-mock');
const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');

const ddbMock = mockClient(DynamoDBClient);

// Set env vars before requiring the handler
process.env.ORDERS_TABLE = 'orders';
process.env.AWS_ENDPOINT_URL = '';

const { handler } = require('../../src/handlers/create-order');

beforeEach(() => {
  ddbMock.reset();
});

describe('createOrder handler', () => {
  test('returns 400 when productId is missing', async () => {
    const event = {
      body: JSON.stringify({ quantity: 2 }),
    };

    const response = await handler(event);

    expect(response.statusCode).toBe(400);
    const body = JSON.parse(response.body);
    expect(body.error).toContain('productId');
  });

  test('creates order and returns 201', async () => {
    ddbMock.on(PutItemCommand).resolves({});

    const event = {
      body: JSON.stringify({ productId: 'prod-123', quantity: 3 }),
    };

    const response = await handler(event);

    expect(response.statusCode).toBe(201);
    const body = JSON.parse(response.body);
    expect(body.orderId).toBeDefined();
    expect(body.status).toBe('pending');
    expect(body.productId).toBe('prod-123');
  });

  test('propagates DynamoDB errors', async () => {
    ddbMock.on(PutItemCommand).rejects(new Error('ProvisionedThroughputExceededException'));

    const event = {
      body: JSON.stringify({ productId: 'prod-123', quantity: 1 }),
    };

    await expect(handler(event)).rejects.toThrow('ProvisionedThroughputExceededException');
  });
});

Run with: npm test -- tests/unit/

Setting Up LocalStack

Start LocalStack before running integration tests:

localstack start -d

Wait for it to be ready:

localstack wait -t 30

Create the DynamoDB table that your integration tests will use:

awslocal dynamodb create-table \
  --table-name orders \
  --attribute-definitions AttributeName=orderId,AttributeType=S \
  --key-schema AttributeName=orderId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

awslocal is a wrapper around aws CLI that points to http://localhost:4566. Install it with pip install awscli-local.

Integration Tests with LocalStack

Integration tests hit the real DynamoDB table running in LocalStack. Set the endpoint URL so the SDK routes there instead of AWS:

// tests/integration/order-flow.test.js
const { DynamoDBClient, GetItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');
const { unmarshall } = require('@aws-sdk/util-dynamodb');

// Point to LocalStack
process.env.AWS_ENDPOINT_URL = 'http://localhost:4566';
process.env.ORDERS_TABLE = 'orders';

const { handler } = require('../../src/handlers/create-order');

const ddb = new DynamoDBClient({
  endpoint: 'http://localhost:4566',
  region: 'us-east-1',
  credentials: { accessKeyId: 'test', secretAccessKey: 'test' },
});

describe('createOrder integration', () => {
  test('persists order to DynamoDB', async () => {
    const event = {
      body: JSON.stringify({ productId: 'prod-456', quantity: 5 }),
    };

    const response = await handler(event);
    expect(response.statusCode).toBe(201);

    const created = JSON.parse(response.body);

    // Verify it actually landed in DynamoDB
    const result = await ddb.send(new GetItemCommand({
      TableName: 'orders',
      Key: { orderId: { S: created.orderId } },
    }));

    expect(result.Item).toBeDefined();
    const item = unmarshall(result.Item);
    expect(item.productId).toBe('prod-456');
    expect(item.quantity).toBe(5);
    expect(item.status).toBe('pending');
  });

  test('multiple orders are independent', async () => {
    const events = [
      { body: JSON.stringify({ productId: 'prod-A', quantity: 1 }) },
      { body: JSON.stringify({ productId: 'prod-B', quantity: 2 }) },
    ];

    const responses = await Promise.all(events.map(e => handler(e)));
    const orders = responses.map(r => JSON.parse(r.body));

    // Each order gets a unique ID
    expect(orders[0].orderId).not.toBe(orders[1].orderId);

    // Both persisted
    for (const order of orders) {
      const result = await ddb.send(new GetItemCommand({
        TableName: 'orders',
        Key: { orderId: { S: order.orderId } },
      }));
      expect(result.Item).toBeDefined();
    }
  });
});

Testing with SAM Local

SAM Local gives you a more complete simulation — it runs your handler inside a Docker container matching the Lambda execution environment.

Invoke a function directly with an event file:

sam local invoke CreateOrderFunction \
  --event events/create-order-event.json \
  --env-vars env.json

Where env.json overrides environment variables:

{
  "CreateOrderFunction": {
    "ORDERS_TABLE": "orders",
    "AWS_ENDPOINT_URL": "http://host.docker.internal:4566"
  }
}

Note: inside Docker containers, localhost refers to the container itself. Use host.docker.internal (Mac/Windows) or the Docker bridge IP (172.17.0.1 on Linux) to reach LocalStack running on the host.

Start the full API Gateway locally:

sam local start-api \
  --env-vars env.json \
  --docker-network host

This spins up a local HTTP server (default port 3000) that routes requests through API Gateway emulation to your Lambda handlers. Test it with curl:

curl -X POST http://localhost:3000/orders \
  -H 'Content-Type: application/json' \
  -d '{"productId": "prod-789", "quantity": 2}'

Testing SQS-Triggered Functions

For event-driven functions triggered by SQS, create the queue in LocalStack and invoke the handler with a synthetic SQS event:

# Create queue in LocalStack
awslocal sqs create-queue --queue-name order-processor

# Get the queue URL
awslocal sqs get-queue-url --queue-name order-processor

Synthetic SQS event for sam local invoke:

{
  "Records": [
    {
      "messageId": "msg-001",
      "receiptHandle": "handle-001",
      "body": "{\"orderId\": \"order-123\", \"action\": \"process\"}",
      "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "1700000000000",
        "SenderId": "AIDAIENQZJOLO23YVJ4VO",
        "ApproximateFirstReceiveTimestamp": "1700000000100"
      },
      "messageAttributes": {},
      "md5OfBody": "...",
      "eventSource": "aws:sqs",
      "eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:order-processor",
      "awsRegion": "us-east-1"
    }
  ]
}

CI Integration

Wire everything together in your CI pipeline:

# .github/workflows/test.yml
name: Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    services:
      localstack:
        image: localstack/localstack:latest
        ports:
          - 4566:4566
        env:
          SERVICES: dynamodb,sqs,s3
        options: >-
          --health-cmd "curl -f http://localhost:4566/_localstack/health"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 10

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      
      - run: npm ci
      
      - name: Run unit tests
        run: npm test -- tests/unit/
      
      - name: Create DynamoDB table
        run: |
          pip install awscli-local
          awslocal dynamodb create-table \
            --table-name orders \
            --attribute-definitions AttributeName=orderId,AttributeType=S \
            --key-schema AttributeName=orderId,KeyType=HASH \
            --billing-mode PAY_PER_REQUEST
      
      - name: Run integration tests
        run: npm test -- tests/integration/
        env:
          AWS_ACCESS_KEY_ID: test
          AWS_SECRET_ACCESS_KEY: test
          AWS_DEFAULT_REGION: us-east-1

Common Pitfalls

DynamoDB marshalling errors: The AWS SDK v3 splits the client from the document client. Use @aws-sdk/lib-dynamodb for automatic marshalling/unmarshalling, or use marshall/unmarshall from @aws-sdk/util-dynamodb manually.

LocalStack cold starts: LocalStack initializes services lazily. The first request to a new service (like DynamoDB) can take a few seconds. Add a small retry loop or a health check before running tests.

Environment variable leakage: Integration tests that set AWS_ENDPOINT_URL will affect other tests in the same process if you don't clean up. Use beforeEach/afterEach to reset, or run unit and integration tests in separate Jest projects.

SAM template drift: It's easy for template.yaml to drift from what's actually deployed. Run sam validate in CI to catch template syntax errors early.

Continuous Monitoring

Local testing catches regressions during development, but Lambda behavior in production can diverge — cold starts under real load, IAM permission errors that LocalStack doesn't enforce, and downstream service failures all happen in production only.

HelpMeTest lets you run end-to-end tests against your deployed Lambda endpoints on a schedule, alerting you the moment behavior changes. You define tests in plain English, and they run continuously against your production API Gateway URLs — no code changes required.

Read more

Start now free