Josnidhin Josnidhin - 6 months ago 153
Node.js Question

How to stub aws-sdk

Lets say I have the following

// file sample.js
var aws = require('aws-sdk');
var dynamoDB = new aws.DynamoDB();

exports.processData = function(){
var data = dynamoDB.getItem(params);
// so something with data
};


How can I write unit tests for the above code sample.

//file sample_test.js
var aws = require('aws-sdk');
var sinon = require('sinon');

// the following code doesnt seem to stub the function
// the actual function is still used in sample.js
var getItemStub = sinon.stub();
aws.DynamoDB.prototype.getItem = getItemStub;

var sample = require('./sample');


What will be a good way to stub the aws-sdk api. I was thinking of using SinonJS to achieve it, but I am open to other libraries and suggestions .

Answer

MY current solution is to expose a function in sample.js like shown below.

function overRide(data) {
  dynamoDB = data.dynamoDB;
}

if(process.env.NODE_ENV === 'test') {
  exports.overRide = overRide;
}

Now in my test case I can do the following which will stub the aws api.

//file sample_test.js
var aws = require('aws-sdk');
var sinon = require('sinon');
var sample = require('./sample');

var ddb = new aws.DynamoDB();
ddb.getItem = sinon.stub();

sample.overRideAWS({dynamoDB: ddb});