Last active
March 6, 2017 11:50
-
-
Save lior-amsalem/78092d6a58af4d71db410592e2ec9702 to your computer and use it in GitHub Desktop.
AWS Mock S3 service for tests in Mocha
This file contains hidden or 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 BUCKET_NAME = 'bucket-assets'; | |
class BucketHandler { | |
constructor(awsModule) { | |
let AWS = require('aws-sdk'); | |
this.s3 = new AWS.S3(); | |
} | |
write(content, filename, callback) { | |
const bucketKey = filename, | |
params = { | |
Bucket: BUCKET_NAME, | |
Key: bucketKey, | |
Body: content | |
}; | |
this.s3.putObject(params, (err, data) => { | |
if (err) { | |
log('[ERROR]', err); | |
} else { | |
log('[SUCCESS] success!'); | |
if (typeof callback === 'function') { | |
callback(data); | |
} | |
} | |
}); | |
} | |
read(content, filename, callback) { | |
const bucketKey = filename, | |
params = { | |
Bucket: BUCKET_NAME, | |
Key: bucketKey, | |
Body: content | |
}; | |
this.s3.getObject(params, (err, data) => { | |
if (err) { | |
log('[ERROR] ' , err); | |
} else { | |
log('[SUCCESS] Success!') | |
if (typeof callback === 'function') { | |
callback(data); | |
} | |
} | |
}); | |
} | |
} | |
module.exports = BucketHandler; |
This file contains hidden or 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 BucketHandler = require('./bucket_handler'), | |
AWS = require('mock-aws'); | |
const bucketHandler = new BucketHandler(); | |
const stubContent = 'test', | |
stubFileName= 'my_file_name3.jpg'; | |
describe('BucketHandler', () => { | |
it('Should write a file successfuly and return stub data', (done) => { | |
AWS.mock('S3', 'putObject', (param, cb) => { | |
cb(null, stubContent); | |
}); | |
bucketHandler.write(stubContent , stubFileName, (data , err) => { | |
expect(data).to.be.equal(stubContent); | |
done(); | |
}); | |
}); | |
it('Should read file', (done) => { | |
AWS.mock('S3', 'getObject', (param, cb) => { | |
cb(null, stubContent); | |
}); | |
bucketHandler.read(stubContent, stubFileName, (data, err) => { | |
expect(data).to.be.equal(stubContent); | |
done(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment