xxxSL
xxxSL

Reputation: 121

Doing a mocha and chai unit testing for node js that need to query from dynamodb

Hi I am new to AWS dynamdoDB and mocha chai unit testing.

I wanted to create a node js unit testing with mocha and chai. In my test.js i need to get expected outcome from AWS dynamoDB. However i not sure how to do it.

in my test.js

var assert = require('chai').assert;

describle('querying items from dynamodb', function(){
     it('find date in Month collection', function(){

 //not sure how should i put my inputs in here.
      });

   })

Do you have any articles or resources that I should read on?

Upvotes: 2

Views: 2945

Answers (1)

Burnest Griffin IV
Burnest Griffin IV

Reputation: 21

If you want to make actual calls to AWS DynamoDB, a simple way to do it would be the following (based on documentation found for DynamoDB and DynamoDB.DocumentClient):

const assert = require('chai').assert;
const AWS = require('aws-sdk');

describe('querying items from dynamodb', function(){
  it('find date in Month collection', function(done){

    var params = {
      TableName : <TEST_TABLE_NAME>,
      Key: {
        <PRIMARY_KEY>: <TEST_KEY_VALUE>
      }
    };

    var expectedDate = <EXPECTED_VALUE>;
    var documentClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
    documentClient.get(params, function(err, data) {
      assert.strictEqual(data.Item.Date, expectedDate);
      done();
    });
  });
});

BUT BUYER BEWARE! This will make calls to your actual DynamoDB and AWS may charge you money! To avoid this, mocking is highly recommended. Mocking calls to your DynamoDB can be done with the following code (based on documentation found on github, npmjs.com, and npmdoc.github.io):

const assert = require('chai').assert;
const AWS = require('aws-sdk');
const MOCK = require('aws-sdk-mock');

describe('querying items from dynamodb', function(){

  before(() => {
    // set up a mock call to DynamoDB
    MOCK.mock('DynamoDB.DocumentClient', 'get', (params, callback) => {
      console.log('Let us not call AWS DynamoDB and say we did.');

      // return fake data
      let fakeData = {
        Item: {
          Date: <FAKE_DATE>
        }
      };

      return callback(null, fakeData);
    });
  });

  after(() => {
    // restore normal function
    MOCK.restore('DynamoDB.DocumentClient');
  });

  it('find date in Month collection', function(done){

    // set up the call like it's real
    var params = {
      TableName : <TEST_TABLE_NAME>,
      Key: {
        <PRIMARY_KEY>: <TEST_KEY_VALUE>
      }
    };

    var expectedDate = <EXPECTED_VALUE>;
    var documentClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
    documentClient.get(params, function(err, data) {
      // data should be the fake object that should match
      assert.strictEqual(data.Item.Date, expectedDate);
      done();
    });
  });
});

Upvotes: 1

Related Questions