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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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)); | |
}); | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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.`); | |
}; |