A lightweight utility library for E2E and integration testing of AWS serverless applications. Trigger your async code locally and use these utilities to verify that records exist in AWS services like DynamoDB.
Testing serverless applications is challenging because operations are often asynchronous. When you trigger a Lambda function or API endpoint, the resulting data might not appear in your data stores immediately. This library provides utilities with built-in retry logic to poll AWS services until your expected data appears - or until a timeout is reached.
Consider writing AUDIT# records to DynamoDB at key points in your async workflows. This provides:
- Traceability - Track the flow of requests through your system
- Testability - Query for audit records to verify specific steps completed
- Debugging - Understand where failures occur in complex flows
// In your Lambda function
await putItem('events-table', {
pk: `ORDER#${orderId}`,
sk: `AUDIT#${Date.now()}#PAYMENT_PROCESSED`,
timestamp: new Date().toISOString(),
correlationId,
status: 'SUCCESS'
});
// In your test
const { items } = await query<AuditRecord>({
tableName: 'events-table',
keyConditionExpression: 'pk = :pk AND begins_with(sk, :prefix)',
expressionAttributeValues: {
':pk': `ORDER#${orderId}`,
':prefix': 'AUDIT#'
}
});
expect(items.some(i => i.sk.includes('PAYMENT_PROCESSED'))).toBe(true);npm install aws-async-assertions
# or
pnpm add aws-async-assertions
# or
yarn add aws-async-assertionsimport { getItem, query, httpCall, generateAccessToken, generateUserAccessToken } from 'aws-async-assertions';
describe('Order Creation E2E', () => {
it('should create an order and persist to DynamoDB', async () => {
// 1. Get an auth token (M2M client credentials via Cognito hosted UI)
const token = await generateAccessToken({
cognitoDomain: 'my-app',
region: 'us-east-1',
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
// Or authenticate as a user (via Cognito InitiateAuth)
// const token = await generateUserAccessToken({
// email: process.env.TEST_EMAIL,
// password: process.env.TEST_PASSWORD,
// });
// 2. Trigger the async flow via API
const order = await httpCall(
'https://api.example.com',
'/orders',
'POST',
{ productId: 'PROD-123', quantity: 2 },
{ Authorization: `Bearer ${token}` }
);
// 3. Wait for and verify the record in DynamoDB (with automatic retries)
const item = await getItem(
{ pk: `ORDER#${order.id}`, sk: 'DETAILS' },
'orders-table',
15, // max 15 attempts
2 // 2 seconds between attempts
);
expect(item.status).toBe('CONFIRMED');
expect(item.quantity).toBe(2);
});
});Retrieves a single item from DynamoDB with automatic retry logic.
const item = await getItem(
{ pk: 'USER#123', sk: 'PROFILE' },
'users-table',
10, // retry up to 10 times
2 // wait 2 seconds between retries
);Queries DynamoDB with automatic retry logic. Supports GSIs, filters, and pagination.
const { items } = await query<Order>({
tableName: 'orders-table',
keyConditionExpression: 'pk = :pk',
expressionAttributeValues: { ':pk': 'USER#123' },
indexName: 'gsi1',
maxIterations: 10,
delayInSeconds: 2
});Inserts or replaces an item in DynamoDB. Useful for setting up test fixtures.
await putItem('users-table', {
pk: 'USER#123',
sk: 'PROFILE',
name: 'Test User',
status: 'ACTIVE'
});Generates an OAuth 2.0 access token using the Cognito hosted UI client credentials flow. All parameters are optional and fall back to environment variables.
// Minimal — uses OAUTH_COGNITO_DOMAIN, AWS_REGION, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET environment variables
const token = await generateAccessToken();
// Explicit overrides
const token = await generateAccessToken({
cognitoDomain: 'my-app',
region: 'us-east-1',
clientId: 'my-client-id',
clientSecret: 'my-client-secret',
scopes: ['read:orders', 'write:orders'],
});Generates an access token using Cognito's InitiateAuth API with the USER_PASSWORD_AUTH flow. region and clientId are optional and fall back to AWS_REGION and USER_POOL_CLIENT_ID environment variables.
// Minimal — uses AWS_REGION and USER_POOL_CLIENT_ID environment variables
const token = await generateUserAccessToken({
email: process.env.TEST_EMAIL,
password: process.env.TEST_PASSWORD,
});
// Explicit overrides
const token = await generateUserAccessToken({
region: 'us-east-1',
clientId: 'my-client-id',
email: process.env.TEST_EMAIL,
password: process.env.TEST_PASSWORD,
});Makes HTTP requests with a 10-second timeout.
const response = await httpCall<CreateOrderResponse>(
'https://api.example.com',
'/orders',
'POST',
{ productId: 'PROD-123' },
{ Authorization: 'Bearer token' }
);Pauses execution for a specified duration.
await delay(5); // Wait 5 secondsGenerates a random UUID-based identifier for unique test data.
const userId = generateRandomId(); // Full UUID: "a1b2c3d4-e5f6-..."
const shortId = generateRandomId(8); // Truncated: "a1b2c3d4".
├── src/
│ ├── cognito/ # Cognito auth utilities (generateAccessToken, generateUserAccessToken)
│ ├── dynamo-db/ # DynamoDB utilities (getItem, putItem, query)
│ ├── utils/ # General utilities (delay, httpCall, etc.)
│ └── index.ts # Main exports
├── docs-site/ # Docusaurus documentation site
└── README.md
- Node.js >= 20
- pnpm 10.29.2
git clone https://github.com/leighton-digital/aws-async-assertions.git
cd aws-async-assertions
pnpm install# Build the library
pnpm build
# Run tests
pnpm test
# Run tests in watch mode
pnpm test:watch
# Generate documentation
pnpm docs:generateThis project uses:
- Biome: Fast linting and formatting
- TypeScript: Type checking
- Jest: Testing framework
- SWC: Fast TypeScript compilation
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Submit a pull request
MIT License - see the LICENSE file for details.
Built with ❤️ by Leighton Digital
