How to mock an Amazon DynamoDB v3 in Nodejs using Jest?

Viewed 1253

I am using an Amazon DynamoDB package from aws-sdk v3 for javascript.
Here is the docs which I have followed: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples.html
I have installed "@aws-sdk/client-dynamodb" package to perform CRUD operations from code.
I have imported commands from package in this way:

import { DynamoDBClient, PutItemCommand, DeleteItemCommand, UpdateItemCommand, GetItemCommand } from "@aws-sdk/client-dynamodb";
const dynamodbClient = new DynamoDBClient({ region: process.env.DYNAMODB_REGION, endpoint: process.env.DYNAMODB_ENDPOINT });
const result = await dynamodbClient.send(new PutItemCommand(params));

I have tried to mock Amazon DynamoDB following Jest docs but it was calling real Amazon DynamoDB in local.

How to mock these "@aws-sdk/client-dynamodb" package in Nodejs?
Please provide an example in Nodejs!

3 Answers

This answer may come a bit late :) Currently there are two very useful package to deal with aws dynamodb mocks

I my case, I ended up using the second option, jest-dynalite since it doesnt require java and its very easy to configure :)

You can use AWSMock along with sinon and mock the method and response as you want. It works really great with jest and it doesn't call a real database.

You should install the aws dynamodb jar and use an endpoint with your dynamodb client.

You can setup a docker container to run dynamodb:

$ docker run -d -p 8000:8000 instructure/dynamo-local-admin:latest

When you setup the dynamodb client for your tests, keep using the endpoint:

import { DynamoDBClient, PutItemCommand, DeleteItemCommand, UpdateItemCommand, GetItemCommand } from "@aws-sdk/client-dynamodb";
const dynamodbClient = new DynamoDBClient({ region: process.env.DYNAMODB_REGION, endpoint: process.env.DYNAMODB_ENDPOINT });
const result = await dynamodbClient.send(new PutItemCommand(params));

After you run your tests, you can check the results on the admin UI available at localhost:8000.

Related