今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

2- AWS Serverless: Testing (typescript)

Hamid Shoja 2026年06月12日 17:31 6 次阅读 来源:Dev.to

Shifting from traditional application testing to serverless TypeScript engineering is all about shifting your perspective: you stop testing a running server, and you start testing how your function responds to events and SDK states. Here is a simple, practical example for each testing, using modern AWS SDK v3 syntax. 1. Unit Testing: Jest + Mock Payloads & SDK Client Mocking In unit tests, you don't call real AWS services. You pass a simulated API Gateway event to your handler, and you mock the AWS SDK so it returns predictable data instead of hitting live infrastructure. The Code Under Test ( src/handler.ts ) import { APIGatewayProxyEvent , APIGatewayProxyResult } from ' aws-lambda ' ; import { DynamoDBClient } from ' @aws-sdk/client-dynamodb ' ; import { DynamoDBDocumentClient , GetCommand } from ' @aws-sdk/lib-dynamodb ' ; const ddbClient = new DynamoDBClient ({}); const docClient = DynamoDBDocumentClient . from ( ddbClient ); export const handler = async ( event : APIGatewayProxyEvent ): Promise < APIGatewayProxyResult > => { const userId = event . pathParameters ?. id ; if ( ! userId ) { return { statusCode : 400 , body : JSON . stringify ({ message : ' Missing ID ' }) }; } // Fetch from DynamoDB const result = await docClient . send ( new GetCommand ({ TableName : process . env . USERS_TABLE , Key : { id : userId } })); if ( ! result . Item ) { return { statusCode : 404 , body : JSON . stringify ({ message : ' User not found ' }) }; } return { statusCode : 200 , body : JSON . stringify ( result . Item ), }; }; The Jest Unit Test ( tests/unit.test.ts ) Instead of the legacy aws-sdk-mock , the modern standard for AWS SDK v3 is aws-sdk-client-mock . import { handler } from ' ../src/handler ' ; import { APIGatewayProxyEvent } from ' aws-lambda ' ; import { mockClient } from ' aws-sdk-client-mock ' ; import { DynamoDBDocumentClient , GetCommand } from ' @aws-sdk/lib-dynamodb ' ; const ddbMock = mockClient ( DynamoDBDocumentClient ); describe ( ' Lambda Handler Unit

本文内容来源于互联网,版权归原作者所有
查看原文