Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 .

like image 633
Josnidhin Avatar asked Apr 25 '15 02:04

Josnidhin


2 Answers

We have created an aws-sdk-mock npm module which mocks out all the AWS SDK services and methods. https://github.com/dwyl/aws-sdk-mock

It's really easy to use. Just call AWS.mock with the service, method and a stub function.

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

Then restore the methods after your tests by calling:

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

Or to restore them all call:

AWS.restore();
like image 165
jruts Avatar answered Nov 18 '22 06:11

jruts


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});
like image 43
Josnidhin Avatar answered Nov 18 '22 06:11

Josnidhin