NodeJs/Mocha Test Case for AWS SDK APIs

Pritam Panhale
2 min readMay 6, 2021

I have searched a lot to write a test case for DynamoDB APIs in node js with mocha. There are lots of materials available and there are many libraries also provided by many groups or individuals.

The main and the important library you can find on the web to write a test case for AWS API is ‘aws-sdk-mock’. I tried adding this library to my project and I found that it's a little bit complicated to write test cases with the approach which was suggested by this library.

In the end, I conclude, I don't want to check/test the code that AWS SDK already provided us. I just want to test the code that I wrote by using AWS’s API.

So I thought, Do I need to really worry about the external frameworks? Can I mock the AWS objects or services the way we usually mock?

Keeping the above thoughts in my mind, I tried mocking the AWS object with regular sinon library and it worked for me. Following is the example.

The Code — ddbDaoService.js

var AWS = require("aws-sdk");createTable = (params) => {
AWS.config.update({
region: <region>,
endpoint: <url>
});

var dynamoDb = new AWS.DynamoDB();
return new Promise((resolve, reject) => {
dynamoDb.createTable(params, function (err, data) {
if (err) {
console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
reject('Unable to create table');
} else {
console.log("Created table - ", JSON.stringify(data, null, 2));
resolve("Created table");
}
});
});
};

The test case -

const ddbDaoService = require('../ddbDaoService');
var AWS = require('aws-sdk');

const sinon = require('sinon');
const assert = require('assert');

describe('DdbDaoService.js Unit Test Cases', () => {
let sandbox;

beforeEach(() => {
sandbox = sinon.createSandbox();
});

afterEach(() => {
sandbox.restore();
});

it('Should create table', async () => {
sandbox.stub(AWS, 'DynamoDB').returns({
createTable: (params, callBack) => {
callBack(null, {TableDescription: {TableName: 'TestTable'}});
}
});

const resp = await ddbDaoService.createTable('testParams');
assert.strictEqual(resp, 'Created table')
});
});

I stubbed the DynamoDB object of the AWS object. I have just provided the simple mock function to ‘createTable’ function as shown above.

Similar to the above code, I have also mocked the other methods from AWS.DynamoDB object like updateTable, deleteTable, etc which I used in my code.

I particularly found this approach easy as my NodeJS application is not a server-based application.

Please share your thoughts also on this approach.

--

--