Reputation: 71
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!
Upvotes: 3
Views: 6622
Reputation: 5926
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)
Upvotes: 2
Reputation: 6622
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
.
Upvotes: 0
Reputation: 193
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.
Upvotes: 1
Reputation: 2105
This answer may come a bit late :) Currently there are two very useful package to deal with aws dynamodb mocks
@aws-sdk/client-dynamodb
I my case, I ended up using the second option, jest-dynalite
since it doesnt require java and its very easy to configure :)
Upvotes: 1