Mock DynamoDB in Typescript

Photo by Chad Kirchoff on Unsplash

In 2021 one of our team priorities is to move toward Serverless architecture. It is tricky to build the unit tests on top of the AWS services. It dragged me a couple of hours to figure out the most comfortable way to mock the DynamoDB functionality.

aws-sdk-mock has a pretty detailed readme and examples for a quick start. The approach is intuitive and clean. When I messed around it in Typescript and Jest, there were a few hiccups that paused me a while without a useful error message. Then I realized that the order of invocation caused unexpected behavior.

Based on the example in the readme, I would emphasize the order of steps to get successful behavior.

Step 1: Mock the AWS instance


Step 2: Mock the DynamoDB function, e.g. put

(params: UpdateItemInput, callback: Function) => {
callback(null, { pk: ‘foo’, sk: ‘bar’ });

The first two parameters are apparent. ‘DynamoDB.DocumentClient’ is the module, and ‘put’ is the function to mock. The third parameter is a callback function to simulate an asynchronous response with your desired data.

Step 3: Create a DynamoDB instance with the mocked AWS instance.

const mockDynamoDB = new AWS.DynamoDB.DocumentClient({
apiVersion: ‘2012–08–10’,

We’ll use the proxied AWS to create a new instance for our further action. It must follow step 2. Otherwise, the instance will call on the real DocumentClient and end up with a confusing error message.

Step 4: To test the mocked put function.

const input = { TableName: ‘’, Item: {} };expect(await mockDynamoDB.put(input).promise()).toEqual({
pk: ‘foo’,
sk: ‘bar’,

Now the mockDynamoDB.put function is successfully mocked with your desired outcome.

Step 5: Restore the mock


To prevent unexpected effect to the rest of your tests, it is always brilliant to reset the mocked work.




Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Spread operator (…) in JavaScript

How to use React Context — Part 1

Getting to know fixture.debugElement : Angular Unit Testing

How to Use Nodemon with NodeJS Apps

React Native for Web — Write Once, Run Anywhere

Build your own operating system-part08

JavaScript Fundamental Concepts

JavaScript Date Constructor Behind the Scene.

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
Anthony Ng

Anthony Ng

Software Engineer

More from Medium

Websocket rooms: Horizontal scaling architectures

Adding dependencies to your Node.js projects

Using an Amazon Simple Queue Service to invoke a Lambda function on LocalStack

Posgres Concurrency Notes: 1