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 .
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();
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With