Saturday, June 2, 2018

Testing AWS Lambda function which uses S3 using Mocha and Sinon

I've been seeking through the interwebz to find a good tutorial on testing an AWS lambda function which uses it's S3 API, so here we go, this is my take on it.
The key idea behind it is to have a 4th default argument which is going to be a Sinon spy at the test, just to mock S3's behaviour. Here we go, there is the solution I came up:

'use strict';
const sinon = require('sinon'),
assert = require('assert'),
copyHandler = require('../index').handler;
describe('copy bucket handler', () => {
const S3 = {
copyObject: sinon.spy()
};
it('copies from XYZ to TARGET_BUCKET/__DATE__/XYZ', () => {
const expectedParams = {
CopySource: 'YOUR_EXPECTED_COPY_SOURCE',
Bucket: 'YOUR_EXPECTED_COPY_BUCKET',
Key: 'YOUR_EXPECTED_KEY'
};
// Here is the trick, we are calling the copyHandler with a 4th argument, which is the spy
copyHandler(event, null, console.log, S3);
assert(S3.copyObject.calledWith(expectedParams));
});
});
'use strict';
const AWS = require('aws-sdk');
const defaultS3 = new AWS.S3({ apiVersion: '2006-03-01' });
exports.handler = (event, context, callback, S3 = defaultS3) => {
const sourcekey = event.fillThisHereWithKeyPath;
const sourceBucket = event.fillThisHereWithBucketPath; // get somewhere from your use case the source bucket / key names
const dest = ''; // define the destination bucket
S3.copyObject({
CopySource: `${srcBucket}/${srcKey}`,
Bucket: destinationBucket,
Key: srcKey
}, (copyErr, copyData) => {
if (copyErr) {
throw `Error: ${copyErr}`;
} else {
console.log('Copied OK');
}
});
// Everything went fine, notify caller.
callback(null, `Copy bucket from ${srcBucket} to ${destinationBucket} done.`);
};
view raw lambda-copy.js hosted with ❤ by GitHub