Testing DynamoDB offline with Serverless Framework

Configuring serverless-dynamodb-local

npm i -D serverless-dynamodb-local
plugins:
- serverless-dynamodb-local
- serverless-offline
custom:
dynamodb:
stages:
- test
start:
inMemory: true
migrate: true

Creating the DynamoDB Resource

resources:
Resources:
DynamoDBTable:
Type: AWS::DynamoDB::Table
DeletionPolicy: Retain
Properties:
TableName: ${self:service}-${self:provider.stage}-event-store
BillingMode: PAY_PER_REQUEST
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S

Configuring Jest

npm i -D @shelf/jest-dynamodb
preset: '@shelf/jest-dynamodb',
jest-dynamodb-config.js

Write code that is easy to test

DynamoDB base client with dazn powertools
DynamoDB base client with standard DocumentClient

Define a custom table name in Jest Environment

Overwriting the environment variables in tests
TableName: ${self:service}-${self:provider.stage}-event-store
DYNAMODB_TABLE: 'typescript-serverless-local-event-store'

Wrapping Up

Full-stack developer. In love with Typescript and Serverless

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store