Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 511
Jayanth Mogadampalli Avatar asked Jan 29 '26 16:01

Jayanth Mogadampalli


1 Answers

AWS recommends mocking DynamoDB and the rest of AWS with aws-sdk-client-mock with documentation included with the module.

Install aws-sdk-client-mock and probably aws-sdk-client-mock-jest

npm i aws-sdk-client-mock aws-sdk-client-mock-jest  

Import the module

import {mockClient} from "aws-sdk-client-mock";
import 'aws-sdk-client-mock-jest';

Create a mock. Reset after each test

describe('Winner purge service', () => {
  const ddbMock = mockClient(DynamoDBClient)

  beforeEach(() => {
    jest.clearAllMocks()
    ddbMock.reset()
  })

Define responses

    ddbMock
        .on(ScanCommand).resolvesOnce({
        Items: [marshall(configItem, {removeUndefinedValues: true})],
        Count: 1
    })
    ddbMock.on(QueryCommand)
        .resolvesOnce({
            Items: [marshall(olderWinner)], Count: 1
        })
        .resolves({
            Items: [], Count: 0
        })

Test calls

expect(ddbMock.commandCalls(DeleteItemCommand).length).toBe(0)
like image 119
Interlated Avatar answered Feb 01 '26 06:02

Interlated