How to stub aws-sdk

Let's say I have

// 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 example.

//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');

      

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

+3


source to share


2 answers


My current solution is to expose the function in sample.js as 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 close 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});

      

+1


source


We've created the aws-sdk-mock npm module that mocks all AWS SDK services and methods. https://github.com/dwyl/aws-sdk-mock

It is very easy to use. Just call AWS.mock with service, method and stub function.

AWS.mock('DynamoDB', 'getItem', function(params, callback) {
    callback(null, 'success');
});

      

Then restore the methods after testing by calling:



AWS.restore('DynamoDB', 'getItem');

      

Or to restore all calls:

AWS.restore();

      

+6


source







All Articles