Skip to content

giuseppe-trisciuoglio/developer-kit / plugins/developer-kit-typescript/skills/aws-lambda-typescript-integration

aws-lambda-typescript-integration

Verified

Provides AWS Lambda integration patterns for TypeScript with cold start optimization. Use when creating or deploying TypeScript Lambda functions, choosing between NestJS framework and raw TypeScript approaches, optimizing cold starts, configuring API Gateway or ALB integration, or implementing serverless TypeScript applications. Triggers include "create lambda typescript", "deploy typescript lambda", "nestjs lambda aws", "raw typescript lambda", "aws lambda typescript performance".

references/testing.md

View on GitHub
# Testing Lambda Functions

Complete guide for testing NestJS Lambda handlers including unit tests, integration tests, and mocking strategies.

## Unit Tests for Handler

Test the Lambda handler in isolation with mocked AWS Lambda context.

```typescript
// lambda.spec.ts
import { handler } from './lambda';
import { Context } from 'aws-lambda';

describe('Lambda Handler', () => {
  const mockContext: Partial<Context> = {
    functionName: 'test-function',
    memoryLimitInMB: '512',
    invokedFunctionArn: 'arn:aws:lambda:us-east-1:123456789:function:test',
    awsRequestId: 'test-request-id',
  };

  beforeEach(() => {
    // Reset cached server for cold start tests
    jest.resetModules();
  });

  it('should bootstrap on first invocation (cold start)', async () => {
    const event = {
      httpMethod: 'GET',
      path: '/api/health',
      headers: {},
      body: null,
    };

    const result = await handler(event, mockContext as Context, () => {});

    expect(result.statusCode).toBe(200);
  });

  it('should reuse instance on warm invocation', async () => {
    const event = {
      httpMethod: 'GET',
      path: '/api/health',
      headers: {},
      body: null,
    };

    // First invocation
    await handler(event, mockContext as Context, () => {});

    // Second invocation (should use cached server)
    const start = Date.now();
    const result = await handler(event, mockContext as Context, () => {});
    const duration = Date.now() - start;

    expect(result.statusCode).toBe(200);
    expect(duration).toBeLessThan(100); // Warm start should be fast
  });
});
```

## Integration Test with serverless-offline

Test the full request/response cycle using the serverless-offline plugin.

```typescript
// test/lambda.integration.spec.ts
describe('Lambda Integration', () => {
  let server: any;

  beforeAll(async () => {
    // Bootstrap for local testing
    const { bootstrap } = await import('../lambda');
    server = await bootstrap();
  });

  afterAll(async () => {
    if (server) {
      // Cleanup
    }
  });

  it('should handle API Gateway events', async () => {
    const event = {
      httpMethod: 'POST',
      path: '/api/users',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: 'Test User' }),
    };

    const result = await server(event, {});

    expect(result.statusCode).toBe(201);
    expect(JSON.parse(result.body)).toHaveProperty('id');
  });
});
```

## Mocking Strategies

### Mock AWS Services

```typescript
// __mocks__/aws-sdk.ts
export const mockSend = jest.fn();

export const DynamoDBClient = jest.fn(() => ({
  send: mockSend,
}));

export const GetItemCommand = jest.fn();
export const PutItemCommand = jest.fn();
```

### Mock NestJS Services

```typescript
// test/mocks/services.mock.ts
export const createMockUserService = () => ({
  findById: jest.fn(),
  create: jest.fn(),
  update: jest.fn(),
  delete: jest.fn(),
});

// In test
const mockUserService = createMockUserService();
mockUserService.findById.mockResolvedValue({ id: '123', name: 'Test' });
```

### Mock Lambda Context

```typescript
// test/utils/lambda-context.ts
import { Context } from 'aws-lambda';

export function createMockContext(overrides?: Partial<Context>): Context {
  return {
    awsRequestId: 'test-request-id',
    functionName: 'test-function',
    memoryLimitInMB: '512',
    invokedFunctionArn: 'arn:aws:lambda:us-east-1:123456789:function:test',
    getRemainingTimeInMillis: () => 30000,
    done: () => {},
    fail: () => {},
    succeed: () => {},
    ...overrides,
  } as Context;
}
```

## Best Practices for Testing

1. **Reset module cache** between tests to test cold/warm start behavior
2. **Mock external services** (DynamoDB, S3, etc.) to avoid real AWS calls
3. **Test both cold and warm starts** to verify caching works correctly
4. **Use realistic event payloads** matching API Gateway format
5. **Measure timing** for warm invocations to detect performance regressions
6. **Test error scenarios** including timeouts and service failures
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 319kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 117kUpdated Claude CodeCodexVerifiedInstall