如何使用TypeScript本地测试AWS Lambda处理器?
本地测试TypeScript编写的APIGateway Lambda:正确定义Event和Context
我按照AWS官方文档创建了基于TypeScript的Lambda函数,现在想本地执行测试,但在定义event和context时遇到问题——空对象{}不满足TypeScript的类型校验要求。
我的处理器代码如下:
import { APIGatewayProxyCallback, Context } from 'aws-lambda'; import { APIGatewayEvent } from "aws-lambda"; export const handler = async ( event: APIGatewayEvent, context: Context, callback: APIGatewayProxyCallback ) => { console.log(`Test`) callback(null, { statusCode: 200, body: JSON.stringify(recordingStatus) }); }
我已经尝试编写了部分event代码,但不确定是否正确:
import { APIGatewayEvent, Context } from 'aws-lambda'; const event : APIGatewayEvent = { body: null, headers: {}, multiValueHeaders: {}, httpMethod: "POST", isBase64Encoded: false, path: "/path/to/resource", pathParameters : null, queryStringParameters : null, multiValueQueryStringParameters : null, stageVariables : null, requestContext: { accountId: "123456789012", apiId: "1234567890", authorizer: {}, protocol: "HTTP/1.1", httpMethod: "POST", identity: { accessKey: null, accountId: null, apiKey : null, apiKeyId : null, caller: null, clientCert: null, cognitoAuthenticationProvider: null, cognitoAuthenticationType: null, cognitoIdentityId: null, cognitoIdentityPoolId: null, principalOrgId : null, sourceIp: "127.0.0.1", userArn: null, userAgent: "Custom User Agent String", user: null }, path: "/prod/path/to/resource", stage: "prod", requestId: "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", requestTime: "09/Apr/2015:12:34:56 +0000", requestTimeEpoch: 1428582896000, resourceId: "123456", resourcePath: "/{proxy+}", }, resource: "/{proxy+}" };
解决方案
1. 完善APIGatewayEvent定义
你写的event已经覆盖了大部分必填字段,注意两个细节:
requestContext里的authorizer如果不需要可以设为null或空对象,TypeScript都允许- 如果处理器用到特定字段(比如
body内容),需根据测试场景填充对应数据
2. 定义Context对象
Context类型有核心必填属性,本地测试只需填充关键字段,其他可选字段按需添加:
const context: Context = { callbackWaitsForEmptyEventLoop: false, functionName: "test-function", functionVersion: "v1", invokedFunctionArn: "arn:aws:lambda:us-east-1:123456789012:function:test-function", memoryLimitInMB: "128", awsRequestId: "test-request-id", logGroupName: "/aws/lambda/test-function", logStreamName: "2024/05/20/[$LATEST]abc123", getRemainingTimeInMillis: () => 30000, // 模拟剩余执行时间 done: () => {}, fail: () => {}, succeed: () => {} };
3. 本地执行测试
创建测试文件(比如local-test.ts),导入处理器和定义好的event、context,直接调用:
import { handler } from './handler'; // 直接在测试文件内定义event和context const event: APIGatewayEvent = { // 你的event内容 }; const context: Context = { // 你的context内容 }; // 定义回调函数处理结果 const callback = (error: any, result: any) => { error ? console.error('执行出错:', error) : console.log('执行结果:', result); }; // 启动测试 handler(event, context, callback);
用ts-node运行测试文件:
ts-node local-test.ts
简化方案:用工具生成测试对象
不想手动写的话,可借助aws-lambda-test-utils快速生成符合类型的测试对象:
npm install aws-lambda-test-utils --save-dev
使用示例:
import { generateAPIGatewayEvent, generateContext } from 'aws-lambda-test-utils'; const event = generateAPIGatewayEvent({ httpMethod: 'POST', path: '/path/to/resource', // 按需添加其他字段 }); const context = generateContext({ functionName: 'test-function' });
内容的提问来源于stack exchange,提问作者Ida Amit
相关产品推荐
相关产品推荐

