Search code examples
javascriptamazon-web-servicesaws-lambdaamazon-dynamodbsinon

How to test a method which returns data from AWS DynamoDB


I have created a new API endpoint in API Gateway mapped my AWS Lambda function and want to write test cases for the JavaScript method which handles requests made to the endpoint. The method creates a connection to AWS DynamoDB using the aws-sdk node module to save passed values to the database and returns a Promise with relevant data. I do not want the spec to trigger a call to the actual DynamoDB or create a new entry to it. I tried using a stub, but it still gave me an error stating that the test-case failed.

Handler.js:

saveUser(userName, logger) {
  const Item = {
    id: uuid.v4(),
    userName,
    ttl: parseInt(Date.now() / 1000) + 900 // expire the name after 15 minutes from now
  };
  const params = {
    TableName: "my-table-name"
  };
  logger.log(`Saving new user name to DynamoDB: ${JSON.stringify(params)}`);

  return new Promise(function(resolve, reject) {
    db.put(params, function(err, _) {
      if (err) {
        logger.exception(`Unable to connect to DynamoDB to create: ${err}`);
        reject({
          statusCode: 404,
          err
        });
      } else {
        logger.log(`Saved data to DynamoDB: ${JSON.stringify(Item)}`);
        resolve({
          statusCode: 201,
          body: Item
        });
      }
    });
  });
}

Handler.spec.js:

import AWS from "aws-sdk";
const db = new AWS.DynamoDB.DocumentClient({
  apiVersion: "2012-08-10"
});

describe("user-name-handler", function() {
  const sandbox = sinon.createSandbox();
  afterEach(() => sandbox.restore());

  it("Test saveUser() method", async function(done) {
    const {
      saveUser
    } = userHandler;

    sandbox.stub(db, "put")
      .returns(new Promise((resolve, _) => resolve({
        statusCode: 200
      })));

    try {
      const result = await saveUser("Sample User", {
        log: () => {},
        exception: () => {}
      });

      expect(result).to.be.equal({
        data: "some data"
      });
      done();
    } catch (err) {
      console.log(err);
      done();
    }
  });
});

Error:

Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.

Solution

  • Try to replace function(done) with function() and remove all the calls to done();