id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
500
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; AWS.config.paramValidation = false; tap.afterEach(function (done) { awsMock.restore(); done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> chore(deps): upgrade devDependencies Modify the tests according to the changes in node-tap. <DFF> @@ -10,9 +10,8 @@ const Readable = require('stream').Readable; AWS.config.paramValidation = false; -tap.afterEach(function (done) { +tap.afterEach(() => { awsMock.restore(); - done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){
1
chore(deps): upgrade devDependencies
2
.js
test
apache-2.0
dwyl/aws-sdk-mock
501
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; AWS.config.paramValidation = false; tap.afterEach(function (done) { awsMock.restore(); done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> chore(deps): upgrade devDependencies Modify the tests according to the changes in node-tap. <DFF> @@ -10,9 +10,8 @@ const Readable = require('stream').Readable; AWS.config.paramValidation = false; -tap.afterEach(function (done) { +tap.afterEach(() => { awsMock.restore(); - done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){
1
chore(deps): upgrade devDependencies
2
.js
test
apache-2.0
dwyl/aws-sdk-mock
502
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn().mockImplementation(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.end(); }); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Fixes issues where jest replace function had an implementation and with calling the mocked method with a single parameter <DFF> @@ -620,6 +620,17 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); + t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { + const jestMock = jest.fn().mockReturnValue('message'); + awsMock.mock('DynamoDB', 'getItem', jestMock); + const db = new AWS.DynamoDB(); + db.getItem(function(err, data){ + st.equal(data, 'message'); + st.equal(jestMock.mock.calls.length, 1); + st.end(); + }); + }); + t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); @@ -632,7 +643,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { - const jestMock = jest.fn().mockImplementation(() => { + const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); @@ -655,6 +666,28 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); + t.test('mock function replaces method with a jest mock with implementation', function(st) { + const jestMock = jest.fn((params, cb) => cb(null, 'item')); + awsMock.mock('DynamoDB', 'getItem', jestMock); + const db = new AWS.DynamoDB(); + db.getItem({}, function(err, data){ + st.equal(jestMock.mock.calls.length, 1); + st.equal(data, 'item'); + st.end(); + }); + }); + + t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { + const jestMock = jest.fn((params, cb) => cb(null, 'item')); + awsMock.mock('DynamoDB', 'getItem', jestMock); + const db = new AWS.DynamoDB(); + db.getItem(function(err, data){ + st.equal(jestMock.mock.calls.length, 1); + st.equal(data, 'item'); + st.end(); + }); + }); + t.end(); });
34
Fixes issues where jest replace function had an implementation and with calling the mocked method with a single parameter
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
503
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn().mockImplementation(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.end(); }); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Fixes issues where jest replace function had an implementation and with calling the mocked method with a single parameter <DFF> @@ -620,6 +620,17 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); + t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { + const jestMock = jest.fn().mockReturnValue('message'); + awsMock.mock('DynamoDB', 'getItem', jestMock); + const db = new AWS.DynamoDB(); + db.getItem(function(err, data){ + st.equal(data, 'message'); + st.equal(jestMock.mock.calls.length, 1); + st.end(); + }); + }); + t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); @@ -632,7 +643,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { - const jestMock = jest.fn().mockImplementation(() => { + const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); @@ -655,6 +666,28 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); + t.test('mock function replaces method with a jest mock with implementation', function(st) { + const jestMock = jest.fn((params, cb) => cb(null, 'item')); + awsMock.mock('DynamoDB', 'getItem', jestMock); + const db = new AWS.DynamoDB(); + db.getItem({}, function(err, data){ + st.equal(jestMock.mock.calls.length, 1); + st.equal(data, 'item'); + st.end(); + }); + }); + + t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { + const jestMock = jest.fn((params, cb) => cb(null, 'item')); + awsMock.mock('DynamoDB', 'getItem', jestMock); + const db = new AWS.DynamoDB(); + db.getItem(function(err, data){ + st.equal(jestMock.mock.calls.length, 1); + st.equal(data, 'item'); + st.end(); + }); + }); + t.end(); });
34
Fixes issues where jest replace function had an implementation and with calling the mocked method with a single parameter
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
504
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> allow spy to return promise rather than call callback <DFF> @@ -136,6 +136,26 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('replacement returns thennable', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params) { + return Promise.resolve('message') + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + return Promise.reject(error) + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise(); + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows');
20
allow spy to return promise rather than call callback
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
505
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> allow spy to return promise rather than call callback <DFF> @@ -136,6 +136,26 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('replacement returns thennable', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params) { + return Promise.resolve('message') + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + return Promise.reject(error) + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise(); + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows');
20
allow spy to return promise rather than call callback
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
506
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); var signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> PR corrections <DFF> @@ -494,7 +494,7 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); - var signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); + var signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); });
1
PR corrections
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
507
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); var signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> PR corrections <DFF> @@ -494,7 +494,7 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); - var signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); + var signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); });
1
PR corrections
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
508
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return promise; } : undefined, createReadStream: function() { return new Readable({ read: function(size) { this.push(null); } }); } }; // If the value of 'replace' is a function we call it with the arguments. } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> fix: backport stream code to node 0.10 <DFF> @@ -137,11 +137,11 @@ function mockServiceMethod(service, client, method, replace) { return promise; } : undefined, createReadStream: function() { - return new Readable({ - read: function(size) { - this.push(null); - } - }); + var stream = new Readable(); + stream._read = function(size) { + this.push(null); + }; + return stream; } }; // If the value of 'replace' is a function we call it with the arguments.
5
fix: backport stream code to node 0.10
5
.js
js
apache-2.0
dwyl/aws-sdk-mock
509
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return promise; } : undefined, createReadStream: function() { return new Readable({ read: function(size) { this.push(null); } }); } }; // If the value of 'replace' is a function we call it with the arguments. } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> fix: backport stream code to node 0.10 <DFF> @@ -137,11 +137,11 @@ function mockServiceMethod(service, client, method, replace) { return promise; } : undefined, createReadStream: function() { - return new Readable({ - read: function(size) { - this.push(null); - } - }); + var stream = new Readable(); + stream._read = function(size) { + this.push(null); + }; + return stream; } }; // If the value of 'replace' is a function we call it with the arguments.
5
fix: backport stream code to node 0.10
5
.js
js
apache-2.0
dwyl/aws-sdk-mock
510
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { console.dir(callback); callback('This is a test error to see if promise rejections go unhandled'); }); var S3 = new AWS.S3(); st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Remove stray console message <DFF> @@ -142,7 +142,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { - console.dir(callback); callback('This is a test error to see if promise rejections go unhandled'); }); var S3 = new AWS.S3();
0
Remove stray console message
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
511
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { console.dir(callback); callback('This is a test error to see if promise rejections go unhandled'); }); var S3 = new AWS.S3(); st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Remove stray console message <DFF> @@ -142,7 +142,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { - console.dir(callback); callback('This is a test error to see if promise rejections go unhandled'); }); var S3 = new AWS.S3();
0
Remove stray console message
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
512
<NME> CONTRIBUTING.md <BEF> ADDFILE <MSG> Create CONTRIBUTING.md <DFF> @@ -0,0 +1,1 @@ +_**Please read** our_ [**contribution guide**](https://github.com/dwyl/contributing) (_thank you_!)
1
Create CONTRIBUTING.md
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
513
<NME> CONTRIBUTING.md <BEF> ADDFILE <MSG> Create CONTRIBUTING.md <DFF> @@ -0,0 +1,1 @@ +_**Please read** our_ [**contribution guide**](https://github.com/dwyl/contributing) (_thank you_!)
1
Create CONTRIBUTING.md
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
514
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.end(); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> When remock is called, update all instances of client <DFF> @@ -113,6 +113,28 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('all instances of service are re-mocked when remock called', function(st){ + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 1'); + }); + const sns1 = new AWS.SNS(); + const sns2 = new AWS.SNS(); + + awsMock.remock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 2'); + }); + + sns1.subscribe({}, function(err, data){ + st.equals(data, 'message 2'); + + sns2.subscribe({}, function(err, data){ + st.equals(data, 'message 2'); + st.end(); + }); + + }); + }); + t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message');
22
When remock is called, update all instances of client
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
515
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.end(); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> When remock is called, update all instances of client <DFF> @@ -113,6 +113,28 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('all instances of service are re-mocked when remock called', function(st){ + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 1'); + }); + const sns1 = new AWS.SNS(); + const sns2 = new AWS.SNS(); + + awsMock.remock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 2'); + }); + + sns1.subscribe({}, function(err, data){ + st.equals(data, 'message 2'); + + sns2.subscribe({}, function(err, data){ + st.equals(data, 'message 2'); + st.end(); + }); + + }); + }); + t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message');
22
When remock is called, update all instances of client
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
516
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); }) }) t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); }) }); }); if (typeof(Promise) === 'function') { callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); var S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { awsMock.mock('Lambda', 'getFunction', function(params) { }); var lambda = new AWS.Lambda(); function P(handler) { var self = this function yay (value) { self.value = value } handler(yay, function(){}) } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P) var promise = lambda.getFunction({}).promise() st.equals(promise.constructor.name, 'P') promise.then(function(data) { st.equals(data, 'message'); st.end(); }); }) } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }) }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equals(data, 'message'); }); st.end(); }) t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e) } }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message') }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge remote-tracking branch 'dwyl/master' into unhandled-rejections <DFF> @@ -14,7 +14,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ @@ -25,8 +25,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); @@ -83,8 +83,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -97,8 +97,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -112,7 +112,7 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); - }) + }); }); }); if (typeof(Promise) === 'function') { @@ -130,12 +130,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); @@ -147,7 +147,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); - }) + }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -162,12 +162,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { @@ -175,21 +175,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); var lambda = new AWS.Lambda(); function P(handler) { - var self = this + var self = this; function yay (value) { - self.value = value + self.value = value; } - handler(yay, function(){}) + handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; - AWS.config.setPromisesDependency(P) - var promise = lambda.getFunction({}).promise() - st.equals(promise.constructor.name, 'P') + AWS.config.setPromisesDependency(P); + var promise = lambda.getFunction({}).promise(); + st.equals(promise.constructor.name, 'P'); promise.then(function(data) { st.equals(data, 'message'); st.end(); }); - }) + }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); @@ -214,7 +214,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -225,7 +225,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -236,7 +236,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -247,7 +247,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -263,7 +263,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -277,7 +277,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -308,7 +308,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -337,7 +337,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); - }) + }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { @@ -352,7 +352,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); - }) + }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); @@ -417,7 +417,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); }); st.end(); - }) + }); t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); @@ -432,7 +432,7 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { - console.log(e) + console.log(e); } }); @@ -447,15 +447,43 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { - awsMock.mock('SNS', 'publish', 'message') + awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); + awsMock.restore(); + + st.end(); + }); + t.end(); +}); + +test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { + t.test('Specific Modules can be set for mocking', function(st) { + var aws2 = require('aws-sdk'); + awsMock.setSDKInstance(aws2); + awsMock.mock('SNS', 'publish', 'message2'); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message2'); + awsMock.restore('SNS'); + st.end(); + }); + }); + + t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { + var bad = {}; + awsMock.setSDKInstance(bad); + st.throws(function() { + awsMock.mock('SNS', 'publish', 'message'); + }); + awsMock.setSDKInstance(AWS); + awsMock.restore(); st.end(); }); t.end();
61
Merge remote-tracking branch 'dwyl/master' into unhandled-rejections
33
.js
test
apache-2.0
dwyl/aws-sdk-mock
517
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); }) }) t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); }) }); }); if (typeof(Promise) === 'function') { callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); var S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { awsMock.mock('Lambda', 'getFunction', function(params) { }); var lambda = new AWS.Lambda(); function P(handler) { var self = this function yay (value) { self.value = value } handler(yay, function(){}) } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P) var promise = lambda.getFunction({}).promise() st.equals(promise.constructor.name, 'P') promise.then(function(data) { st.equals(data, 'message'); st.end(); }); }) } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }) }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equals(data, 'message'); }); st.end(); }) t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e) } }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message') }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge remote-tracking branch 'dwyl/master' into unhandled-rejections <DFF> @@ -14,7 +14,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ @@ -25,8 +25,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); @@ -83,8 +83,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -97,8 +97,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -112,7 +112,7 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); - }) + }); }); }); if (typeof(Promise) === 'function') { @@ -130,12 +130,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); @@ -147,7 +147,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); - }) + }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -162,12 +162,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { @@ -175,21 +175,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); var lambda = new AWS.Lambda(); function P(handler) { - var self = this + var self = this; function yay (value) { - self.value = value + self.value = value; } - handler(yay, function(){}) + handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; - AWS.config.setPromisesDependency(P) - var promise = lambda.getFunction({}).promise() - st.equals(promise.constructor.name, 'P') + AWS.config.setPromisesDependency(P); + var promise = lambda.getFunction({}).promise(); + st.equals(promise.constructor.name, 'P'); promise.then(function(data) { st.equals(data, 'message'); st.end(); }); - }) + }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); @@ -214,7 +214,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -225,7 +225,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -236,7 +236,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -247,7 +247,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -263,7 +263,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -277,7 +277,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -308,7 +308,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -337,7 +337,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); - }) + }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { @@ -352,7 +352,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); - }) + }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); @@ -417,7 +417,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); }); st.end(); - }) + }); t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); @@ -432,7 +432,7 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { - console.log(e) + console.log(e); } }); @@ -447,15 +447,43 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { - awsMock.mock('SNS', 'publish', 'message') + awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); + awsMock.restore(); + + st.end(); + }); + t.end(); +}); + +test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { + t.test('Specific Modules can be set for mocking', function(st) { + var aws2 = require('aws-sdk'); + awsMock.setSDKInstance(aws2); + awsMock.mock('SNS', 'publish', 'message2'); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message2'); + awsMock.restore('SNS'); + st.end(); + }); + }); + + t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { + var bad = {}; + awsMock.setSDKInstance(bad); + st.throws(function() { + awsMock.mock('SNS', 'publish', 'message'); + }); + awsMock.setSDKInstance(AWS); + awsMock.restore(); st.end(); }); t.end();
61
Merge remote-tracking branch 'dwyl/master' into unhandled-rejections
33
.js
test
apache-2.0
dwyl/aws-sdk-mock
518
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. ***Beginners Guide to AWS Lambda***: https://github.com/dwyl/learn-aws-lambda ## Why? Testing your code is *essential* everywhere you need *reliability*. ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); ## Background Reading * (Mocking using Sinon.js)[http://sinonjs.org/docs/] * (AWS Lambda)[https://github.com/dwyl/learn-aws-lambda] **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Adds table of contents to Readme <DFF> @@ -17,6 +17,12 @@ please checkout our our ***Beginners Guide to AWS Lambda***: https://github.com/dwyl/learn-aws-lambda +* [Why](#why) +* [What](#what) +* [Getting Started](#how) +* [Documentation](#documentation) +* [Background Reading](#background-reading) + ## Why? Testing your code is *essential* everywhere you need *reliability*. @@ -108,7 +114,7 @@ i.e. equivalent to a 'restore all' function. ## Background Reading -* (Mocking using Sinon.js)[http://sinonjs.org/docs/] -* (AWS Lambda)[https://github.com/dwyl/learn-aws-lambda] +* [Mocking using Sinon.js](http://sinonjs.org/docs/) +* [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving**
8
Adds table of contents to Readme
2
.md
md
apache-2.0
dwyl/aws-sdk-mock
519
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. ***Beginners Guide to AWS Lambda***: https://github.com/dwyl/learn-aws-lambda ## Why? Testing your code is *essential* everywhere you need *reliability*. ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); ## Background Reading * (Mocking using Sinon.js)[http://sinonjs.org/docs/] * (AWS Lambda)[https://github.com/dwyl/learn-aws-lambda] **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Adds table of contents to Readme <DFF> @@ -17,6 +17,12 @@ please checkout our our ***Beginners Guide to AWS Lambda***: https://github.com/dwyl/learn-aws-lambda +* [Why](#why) +* [What](#what) +* [Getting Started](#how) +* [Documentation](#documentation) +* [Background Reading](#background-reading) + ## Why? Testing your code is *essential* everywhere you need *reliability*. @@ -108,7 +114,7 @@ i.e. equivalent to a 'restore all' function. ## Background Reading -* (Mocking using Sinon.js)[http://sinonjs.org/docs/] -* (AWS Lambda)[https://github.com/dwyl/learn-aws-lambda] +* [Mocking using Sinon.js](http://sinonjs.org/docs/) +* [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving**
8
Adds table of contents to Readme
2
.md
md
apache-2.0
dwyl/aws-sdk-mock
520
<NME> index.test.js <BEF> ADDFILE <MSG> Merge pull request #2 from dwyl/v1 V1of module <DFF> @@ -0,0 +1,104 @@ +var test = require('tape'); +var awsMock = require('../index.js'); +var AWS = require('aws-sdk'); + +test('AWS.mock function should mock AWS service and method on the service', function(t){ + t.test('mock function replaces method with a function that returns replace string', function(st){ + awsMock.mock('SNS', 'publish', 'message'); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }); + t.test('mock function replaces method with replace function', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }) + t.test('method is not re-mocked if a mock already exists', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "test"); + }); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }) + t.test('service is not re-mocked if a mock already exists', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, "test"); + }); + sns.subscribe({}, function(err, data){ + st.equals(data, 'test'); + awsMock.restore('SNS'); + st.end(); + }) + }) + t.test('all the methods on a service are restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + st.equals(AWS.SNS.isSinonProxy, true); + + awsMock.restore('SNS'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.end(); + }) + t.test('only the method on the service is restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(sns.publish.isSinonProxy, true); + + awsMock.restore('SNS', 'publish'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); + st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); + st.end(); + }) + t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + awsMock.mock('DynamoDB', 'putItem', function(params, callback){ + callback(null, "test"); + }); + var sns = new AWS.SNS(); + var dynamoDb = new AWS.DynamoDB(); + + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(sns.publish.isSinonProxy, true); + st.equals(dynamoDb.putItem.isSinonProxy, true); + + awsMock.restore(); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); + st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); + st.end(); + }) + t.end(); +});
104
Merge pull request #2 from dwyl/v1
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
521
<NME> index.test.js <BEF> ADDFILE <MSG> Merge pull request #2 from dwyl/v1 V1of module <DFF> @@ -0,0 +1,104 @@ +var test = require('tape'); +var awsMock = require('../index.js'); +var AWS = require('aws-sdk'); + +test('AWS.mock function should mock AWS service and method on the service', function(t){ + t.test('mock function replaces method with a function that returns replace string', function(st){ + awsMock.mock('SNS', 'publish', 'message'); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }); + t.test('mock function replaces method with replace function', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }) + t.test('method is not re-mocked if a mock already exists', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "test"); + }); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }) + t.test('service is not re-mocked if a mock already exists', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, "test"); + }); + sns.subscribe({}, function(err, data){ + st.equals(data, 'test'); + awsMock.restore('SNS'); + st.end(); + }) + }) + t.test('all the methods on a service are restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + st.equals(AWS.SNS.isSinonProxy, true); + + awsMock.restore('SNS'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.end(); + }) + t.test('only the method on the service is restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + var sns = new AWS.SNS(); + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(sns.publish.isSinonProxy, true); + + awsMock.restore('SNS', 'publish'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); + st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); + st.end(); + }) + t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, "message"); + }); + awsMock.mock('DynamoDB', 'putItem', function(params, callback){ + callback(null, "test"); + }); + var sns = new AWS.SNS(); + var dynamoDb = new AWS.DynamoDB(); + + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(sns.publish.isSinonProxy, true); + st.equals(dynamoDb.putItem.isSinonProxy, true); + + awsMock.restore(); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); + st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); + st.end(); + }) + t.end(); +});
104
Merge pull request #2 from dwyl/v1
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
522
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); st.end(); }) }) t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> You can now mock out multiple methods on the same service <DFF> @@ -51,6 +51,22 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }) }) + t.test('multiple methods can be mocked on the same service', function(st){ + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}, function(err, data) { + st.equals(data, 'message'); + lambda.createFunction({}, function(err, data) { + st.equals(data, 'message'); + st.end(); + }) + }); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
16
You can now mock out multiple methods on the same service
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
523
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); st.end(); }) }) t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> You can now mock out multiple methods on the same service <DFF> @@ -51,6 +51,22 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }) }) + t.test('multiple methods can be mocked on the same service', function(st){ + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}, function(err, data) { + st.equals(data, 'message'); + lambda.createFunction({}, function(err, data) { + st.equals(data, 'message'); + st.end(); + }) + }); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
16
You can now mock out multiple methods on the same service
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
524
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; */ function mockServiceMethod(service, client, method, replace) { services[service].methodMocks[method].stub = sinon.stub(client, method, function() { // If the value of 'replace' is a function we call it with the arguments. if(typeof(replace) === 'function') { return replace.apply(replace, arguments); } // Else we call the callback with the value of 'replace'. else { var callback = arguments[arguments.length - 1]; return callback(null, replace); } }); } /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; delete services[service].methodMocks[method]; } module.exports = AWS; if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Add support for mocking AWS SDK's promises As of March 31, 2016 [the AWS SDK now supports Promises](https://blogs.aws.amazon.com/javascript/post/Tx3BZ2DC4XARUGG/Support-for-Promises-in-the-SDK). This means that you can now do things like this: ```js var s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'us-west-2'}); var params = { Bucket: 'bucket', Key: 'example2.txt', Body: 'Uploaded text using the promise-based method!' }; var putObjectPromise = s3.putObject(params).promise(); putObjectPromise.then(function(data) { console.log('Success'); }).catch(function(err) { console.log(err); }); ``` Attempting to use aws-sdk-mock to mock methods that now no longer require a callback function causes issues, most notably: `TypeError: callback is not a function`. This PR attempts to resolve this issue by checking to see if the mocked method was passed a callback function. If it was passed a callback function then everything should behave exactly as it did before. But if it wasn't then it returns an object containing a single method `promise` which, when invoked, will execute the user's mocked response and the promise will branch based on what the callback returns. It will utilize the native/global promise if available, but it will also pick up on calls to `AWS.config.setPromisesDependency` so that the mocks can create new promises with the provided promise constructor. <DFF> @@ -84,15 +84,32 @@ function mockService(service) { */ function mockServiceMethod(service, client, method, replace) { services[service].methodMocks[method].stub = sinon.stub(client, method, function() { - // If the value of 'replace' is a function we call it with the arguments. - if(typeof(replace) === 'function') { - return replace.apply(replace, arguments); - } - // Else we call the callback with the value of 'replace'. - else { - var callback = arguments[arguments.length - 1]; - return callback(null, replace); + var args = Array.prototype.slice.call(arguments); + + // If the method was called w/o a callback function, assume they are consuming a Promise + if(typeof(AWS.Promise) === 'function' && typeof(args[args.length - 1]) !== 'function') { + return { + promise: function() { + return new AWS.Promise(function(resolve, reject) { + // Provide a callback function for the mock to invoke + args.push(function(err, val) { return err ? reject(err) : resolve(val) }) + return invokeMock() + }) + } + } } + + return (function invokeMock() { + // If the value of 'replace' is a function we call it with the arguments. + if(typeof(replace) === 'function') { + return replace.apply(replace, args); + } + // Else we call the callback with the value of 'replace'. + else { + var callback = args[args.length - 1]; + return callback(null, replace); + } + })() }); } @@ -151,4 +168,15 @@ function restoreMethod(service, method) { delete services[service].methodMocks[method]; } +(function(){ + var setPromisesDependency = _AWS.config.setPromisesDependency; + if (typeof(setPromisesDependency) === 'function') { + AWS.Promise = typeof(Promise) === 'function' ? Promise : null; + _AWS.config.setPromisesDependency = function(p) { + AWS.Promise = p; + return setPromisesDependency(p); + }; + } +})() + module.exports = AWS;
36
Add support for mocking AWS SDK's promises
8
.js
js
apache-2.0
dwyl/aws-sdk-mock
525
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; */ function mockServiceMethod(service, client, method, replace) { services[service].methodMocks[method].stub = sinon.stub(client, method, function() { // If the value of 'replace' is a function we call it with the arguments. if(typeof(replace) === 'function') { return replace.apply(replace, arguments); } // Else we call the callback with the value of 'replace'. else { var callback = arguments[arguments.length - 1]; return callback(null, replace); } }); } /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; delete services[service].methodMocks[method]; } module.exports = AWS; if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Add support for mocking AWS SDK's promises As of March 31, 2016 [the AWS SDK now supports Promises](https://blogs.aws.amazon.com/javascript/post/Tx3BZ2DC4XARUGG/Support-for-Promises-in-the-SDK). This means that you can now do things like this: ```js var s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'us-west-2'}); var params = { Bucket: 'bucket', Key: 'example2.txt', Body: 'Uploaded text using the promise-based method!' }; var putObjectPromise = s3.putObject(params).promise(); putObjectPromise.then(function(data) { console.log('Success'); }).catch(function(err) { console.log(err); }); ``` Attempting to use aws-sdk-mock to mock methods that now no longer require a callback function causes issues, most notably: `TypeError: callback is not a function`. This PR attempts to resolve this issue by checking to see if the mocked method was passed a callback function. If it was passed a callback function then everything should behave exactly as it did before. But if it wasn't then it returns an object containing a single method `promise` which, when invoked, will execute the user's mocked response and the promise will branch based on what the callback returns. It will utilize the native/global promise if available, but it will also pick up on calls to `AWS.config.setPromisesDependency` so that the mocks can create new promises with the provided promise constructor. <DFF> @@ -84,15 +84,32 @@ function mockService(service) { */ function mockServiceMethod(service, client, method, replace) { services[service].methodMocks[method].stub = sinon.stub(client, method, function() { - // If the value of 'replace' is a function we call it with the arguments. - if(typeof(replace) === 'function') { - return replace.apply(replace, arguments); - } - // Else we call the callback with the value of 'replace'. - else { - var callback = arguments[arguments.length - 1]; - return callback(null, replace); + var args = Array.prototype.slice.call(arguments); + + // If the method was called w/o a callback function, assume they are consuming a Promise + if(typeof(AWS.Promise) === 'function' && typeof(args[args.length - 1]) !== 'function') { + return { + promise: function() { + return new AWS.Promise(function(resolve, reject) { + // Provide a callback function for the mock to invoke + args.push(function(err, val) { return err ? reject(err) : resolve(val) }) + return invokeMock() + }) + } + } } + + return (function invokeMock() { + // If the value of 'replace' is a function we call it with the arguments. + if(typeof(replace) === 'function') { + return replace.apply(replace, args); + } + // Else we call the callback with the value of 'replace'. + else { + var callback = args[args.length - 1]; + return callback(null, replace); + } + })() }); } @@ -151,4 +168,15 @@ function restoreMethod(service, method) { delete services[service].methodMocks[method]; } +(function(){ + var setPromisesDependency = _AWS.config.setPromisesDependency; + if (typeof(setPromisesDependency) === 'function') { + AWS.Promise = typeof(Promise) === 'function' ? Promise : null; + _AWS.config.setPromisesDependency = function(p) { + AWS.Promise = p; + return setPromisesDependency(p); + }; + } +})() + module.exports = AWS;
36
Add support for mocking AWS SDK's promises
8
.js
js
apache-2.0
dwyl/aws-sdk-mock
526
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn().mockImplementation(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Reduce indentation in jest "throw" test/index.test.js Co-authored-by: Abe Tomoaki <c9a2a5540dcfc3ebad99e723223675d3f15edc54@enzou.tokyo> <DFF> @@ -633,7 +633,7 @@ test('AWS.mock function should mock AWS service and method on the service', func t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn().mockImplementation(() => { - throw new Error('something went wrong') + throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB();
1
Reduce indentation in jest "throw" test/index.test.js
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
527
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn().mockImplementation(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Reduce indentation in jest "throw" test/index.test.js Co-authored-by: Abe Tomoaki <c9a2a5540dcfc3ebad99e723223675d3f15edc54@enzou.tokyo> <DFF> @@ -633,7 +633,7 @@ test('AWS.mock function should mock AWS service and method on the service', func t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn().mockImplementation(() => { - throw new Error('something went wrong') + throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB();
1
Reduce indentation in jest "throw" test/index.test.js
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
528
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Fixed minor markdown formatting issue <DFF> @@ -23,7 +23,7 @@ https://github.com/dwyl/learn-aws-lambda * [Documentation](#documentation) * [Background Reading](#background-reading) -## Why? +## Why? Testing your code is *essential* everywhere you need *reliability*.
1
Fixed minor markdown formatting issue
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
529
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Fixed minor markdown formatting issue <DFF> @@ -23,7 +23,7 @@ https://github.com/dwyl/learn-aws-lambda * [Documentation](#documentation) * [Background Reading](#background-reading) -## Why? +## Why? Testing your code is *essential* everywhere you need *reliability*.
1
Fixed minor markdown formatting issue
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
530
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): var AWS_SDK = require('aws-sdk') AWS.setSDKInstance(AWS_SDK); ### Configuring promises } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #65 from Starefossen/patch-1 Add missing closing code block to README <DFF> @@ -178,6 +178,7 @@ var AWS = require('aws-sdk-mock'); var AWS_SDK = require('aws-sdk') AWS.setSDKInstance(AWS_SDK); +``` ### Configuring promises
1
Merge pull request #65 from Starefossen/patch-1
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
531
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): var AWS_SDK = require('aws-sdk') AWS.setSDKInstance(AWS_SDK); ### Configuring promises } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #65 from Starefossen/patch-1 Add missing closing code block to README <DFF> @@ -178,6 +178,7 @@ var AWS = require('aws-sdk-mock'); var AWS_SDK = require('aws-sdk') AWS.setSDKInstance(AWS_SDK); +``` ### Configuring promises
1
Merge pull request #65 from Starefossen/patch-1
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
532
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; } /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Removed bitwise operator for more readability <DFF> @@ -32,7 +32,7 @@ AWS.mock = function(service, method, replace) { services[service].methodMocks = [] mockService(service, method, replace); } else { - var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; + var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; }
1
Removed bitwise operator for more readability
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
533
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; } /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Removed bitwise operator for more readability <DFF> @@ -32,7 +32,7 @@ AWS.mock = function(service, method, replace) { services[service].methodMocks = [] mockService(service, method, replace); } else { - var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; + var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; }
1
Removed bitwise operator for more readability
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
534
<NME> LICENSE <BEF> ADDFILE <MSG> add Apache 2.0 license file fixes https://github.com/dwyl/aws-sdk-mock/issues/71 <DFF> @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2012-2018 dwyl.com + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.
202
add Apache 2.0 license file fixes https://github.com/dwyl/aws-sdk-mock/issues/71
0
LICENSE
apache-2.0
dwyl/aws-sdk-mock
535
<NME> LICENSE <BEF> ADDFILE <MSG> add Apache 2.0 license file fixes https://github.com/dwyl/aws-sdk-mock/issues/71 <DFF> @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2012-2018 dwyl.com + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.
202
add Apache 2.0 license file fixes https://github.com/dwyl/aws-sdk-mock/issues/71
0
LICENSE
apache-2.0
dwyl/aws-sdk-mock
536
<NME> index.test-d.ts <BEF> import * as AWS from 'aws-sdk'; import { AWSError } from 'aws-sdk'; import { ListObjectsV2Request } from 'aws-sdk/clients/s3'; import { expectError, expectType } from 'tsd'; import { mock, remock, restore, setSDK, setSDKInstance } from '../index'; const awsError: AWSError = { name: 'AWSError', message: 'message', code: 'code', time: new Date(), }; expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); const output: AWS.S3.ListObjectsV2Output = { Name: params.Bucket, MaxKeys: params.MaxKeys, Delimiter: params.Delimiter, Prefix: params.Prefix, KeyCount: 1, IsTruncated: false, ContinuationToken: params.ContinuationToken, Contents: [ { LastModified: new Date(), ETag: '"668d791b0c7d6a7f0f86c269888b4546"', StorageClass: 'STANDARD', Key: 'aws-sdk-mock/index.js', Size: 8524, }, ] }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectError(mock('S3', 'describeObjects', (params, callback) => { expectType<never>(params); expectType<never>(callback); })); expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen')); expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen')); expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen')); expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen')); expectError(mock('StaticDB', 'getItem', "it couldn't")); expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { // $ExpectType string[] const instanceIds = params.InstanceIds; expectType<string[]>(instanceIds); const output: AWS.EC2.StopInstancesResult = { StoppingInstances: instanceIds.map(id => ({ InstanceId: id, PreviousState: { Name: 'running' }, CurrentState: { Name: 'stopping' }, })), }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectType<void>(remock('Snowball', 'makeRequest', undefined)); expectError(remock('Snowball', 'throwRequest', undefined)); expectType<void>(restore('Pricing', 'getProducts')); expectError(restore('Pricing', 'borrowMoney')); expectType<void>(restore('KMS')); expectError(restore('Skynet')); expectError(restore(42)); expectType<void>(restore()); expectError(restore(null)); expectType<void>(setSDK('aws-sdk')); expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk'))); async function foo() { expectType<void>(setSDKInstance(await import('aws-sdk'))); } expectError(setSDKInstance(AWS.S3)); import allClients = require('aws-sdk/clients/all'); expectError(setSDKInstance(allClients)); <MSG> Merge pull request #262 from thomaux/fix-259 #259: support nested client names for remock and restore methods <DFF> @@ -11,6 +11,9 @@ const awsError: AWSError = { time: new Date(), }; +/** + * mock + */ expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); @@ -83,16 +86,30 @@ expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { expectError(callback(awsError, output)); })); +/** + * Remock + */ expectType<void>(remock('Snowball', 'makeRequest', undefined)); +expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined)); + expectError(remock('Snowball', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentServer', 'get', undefined)); +/** + * Restore + */ expectType<void>(restore('Pricing', 'getProducts')); +expectType<void>(restore('DynamoDB.DocumentClient', 'get')); expectError(restore('Pricing', 'borrowMoney')); +expectError(restore('DynamoDB.DocumentClient', 'unknown')); expectType<void>(restore('KMS')); +expectType<void>(restore('DynamoDB.DocumentClient')); expectError(restore('Skynet')); +expectError(restore('DynamoDB.DocumentServer')); expectError(restore(42)); @@ -100,8 +117,14 @@ expectType<void>(restore()); expectError(restore(null)); +/** + * setSDK + */ expectType<void>(setSDK('aws-sdk')); +/** + * setSDKInstance + */ expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk')));
23
Merge pull request #262 from thomaux/fix-259
0
.ts
test-d
apache-2.0
dwyl/aws-sdk-mock
537
<NME> index.test-d.ts <BEF> import * as AWS from 'aws-sdk'; import { AWSError } from 'aws-sdk'; import { ListObjectsV2Request } from 'aws-sdk/clients/s3'; import { expectError, expectType } from 'tsd'; import { mock, remock, restore, setSDK, setSDKInstance } from '../index'; const awsError: AWSError = { name: 'AWSError', message: 'message', code: 'code', time: new Date(), }; expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); const output: AWS.S3.ListObjectsV2Output = { Name: params.Bucket, MaxKeys: params.MaxKeys, Delimiter: params.Delimiter, Prefix: params.Prefix, KeyCount: 1, IsTruncated: false, ContinuationToken: params.ContinuationToken, Contents: [ { LastModified: new Date(), ETag: '"668d791b0c7d6a7f0f86c269888b4546"', StorageClass: 'STANDARD', Key: 'aws-sdk-mock/index.js', Size: 8524, }, ] }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectError(mock('S3', 'describeObjects', (params, callback) => { expectType<never>(params); expectType<never>(callback); })); expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen')); expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen')); expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen')); expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen')); expectError(mock('StaticDB', 'getItem', "it couldn't")); expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { // $ExpectType string[] const instanceIds = params.InstanceIds; expectType<string[]>(instanceIds); const output: AWS.EC2.StopInstancesResult = { StoppingInstances: instanceIds.map(id => ({ InstanceId: id, PreviousState: { Name: 'running' }, CurrentState: { Name: 'stopping' }, })), }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectType<void>(remock('Snowball', 'makeRequest', undefined)); expectError(remock('Snowball', 'throwRequest', undefined)); expectType<void>(restore('Pricing', 'getProducts')); expectError(restore('Pricing', 'borrowMoney')); expectType<void>(restore('KMS')); expectError(restore('Skynet')); expectError(restore(42)); expectType<void>(restore()); expectError(restore(null)); expectType<void>(setSDK('aws-sdk')); expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk'))); async function foo() { expectType<void>(setSDKInstance(await import('aws-sdk'))); } expectError(setSDKInstance(AWS.S3)); import allClients = require('aws-sdk/clients/all'); expectError(setSDKInstance(allClients)); <MSG> Merge pull request #262 from thomaux/fix-259 #259: support nested client names for remock and restore methods <DFF> @@ -11,6 +11,9 @@ const awsError: AWSError = { time: new Date(), }; +/** + * mock + */ expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); @@ -83,16 +86,30 @@ expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { expectError(callback(awsError, output)); })); +/** + * Remock + */ expectType<void>(remock('Snowball', 'makeRequest', undefined)); +expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined)); + expectError(remock('Snowball', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentServer', 'get', undefined)); +/** + * Restore + */ expectType<void>(restore('Pricing', 'getProducts')); +expectType<void>(restore('DynamoDB.DocumentClient', 'get')); expectError(restore('Pricing', 'borrowMoney')); +expectError(restore('DynamoDB.DocumentClient', 'unknown')); expectType<void>(restore('KMS')); +expectType<void>(restore('DynamoDB.DocumentClient')); expectError(restore('Skynet')); +expectError(restore('DynamoDB.DocumentServer')); expectError(restore(42)); @@ -100,8 +117,14 @@ expectType<void>(restore()); expectError(restore(null)); +/** + * setSDK + */ expectType<void>(setSDK('aws-sdk')); +/** + * setSDKInstance + */ expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk')));
23
Merge pull request #262 from thomaux/fix-259
0
.ts
test-d
apache-2.0
dwyl/aws-sdk-mock
538
<NME> .gitignore <BEF> node_modules/ coverage/ .DS_Store .nyc_output <MSG> add package-lock.json to .gitignore (super noisy file!) <DFF> @@ -2,3 +2,4 @@ node_modules/ coverage/ .DS_Store .nyc_output +package-lock.json \ No newline at end of file
1
add package-lock.json to .gitignore (super noisy file!)
0
gitignore
apache-2.0
dwyl/aws-sdk-mock
539
<NME> .gitignore <BEF> node_modules/ coverage/ .DS_Store .nyc_output <MSG> add package-lock.json to .gitignore (super noisy file!) <DFF> @@ -2,3 +2,4 @@ node_modules/ coverage/ .DS_Store .nyc_output +package-lock.json \ No newline at end of file
1
add package-lock.json to .gitignore (super noisy file!)
0
gitignore
apache-2.0
dwyl/aws-sdk-mock
540
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data // or AWS.restore(); this will restore all the methods and services ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #61 from aaronbruckner/ReadmeUpdateWithSinon Readme Update With Sinon Spy Usage <DFF> @@ -62,6 +62,27 @@ AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` +You can also pass Sinon spies to the mock: + +```js +var updateTableSpy = sinon.spy(); +AWS.mock('DynamoDB', 'updateTable', updateTableSpy); + +// Object under test +myDynamoManager.scaleDownTable(); + +// Assert on your Sinon spy as normal +assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); +var expectedParams = { + TableName: 'testTableName', + ProvisionedThroughput: { + ReadCapacityUnits: 1, + WriteCapacityUnits: 1 + } +}; +assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); +``` + **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1:
21
Merge pull request #61 from aaronbruckner/ReadmeUpdateWithSinon
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
541
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data // or AWS.restore(); this will restore all the methods and services ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #61 from aaronbruckner/ReadmeUpdateWithSinon Readme Update With Sinon Spy Usage <DFF> @@ -62,6 +62,27 @@ AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` +You can also pass Sinon spies to the mock: + +```js +var updateTableSpy = sinon.spy(); +AWS.mock('DynamoDB', 'updateTable', updateTableSpy); + +// Object under test +myDynamoManager.scaleDownTable(); + +// Assert on your Sinon spy as normal +assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); +var expectedParams = { + TableName: 'testTableName', + ProvisionedThroughput: { + ReadCapacityUnits: 1, + WriteCapacityUnits: 1 + } +}; +assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); +``` + **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1:
21
Merge pull request #61 from aaronbruckner/ReadmeUpdateWithSinon
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
542
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS = require('aws-sdk'); AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> fix import syntax <DFF> @@ -207,7 +207,7 @@ Example: ```js // test code const AWSMock = require('aws-sdk-mock'); -import AWS = require('aws-sdk'); +import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */);
1
fix import syntax
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
543
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS = require('aws-sdk'); AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> fix import syntax <DFF> @@ -207,7 +207,7 @@ Example: ```js // test code const AWSMock = require('aws-sdk-mock'); -import AWS = require('aws-sdk'); +import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */);
1
fix import syntax
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
544
<NME> workflow.yml <BEF> name: Node CI on: [push, pull_request] jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: node-version: [12.x, 14.x, 16.x, 18.x] os: [ubuntu-latest, windows-latest, macos-latest] steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} - run: npm i - run: npm test <MSG> Merge pull request #255 from abetomo/feature/add_lint_to_ci ci: add a lint task to ci <DFF> @@ -15,4 +15,5 @@ jobs: with: node-version: ${{ matrix.node-version }} - run: npm i + - run: npm run lint - run: npm test
1
Merge pull request #255 from abetomo/feature/add_lint_to_ci
0
.yml
github/workflows/workflow
apache-2.0
dwyl/aws-sdk-mock
545
<NME> workflow.yml <BEF> name: Node CI on: [push, pull_request] jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: node-version: [12.x, 14.x, 16.x, 18.x] os: [ubuntu-latest, windows-latest, macos-latest] steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} - run: npm i - run: npm test <MSG> Merge pull request #255 from abetomo/feature/add_lint_to_ci ci: add a lint task to ci <DFF> @@ -15,4 +15,5 @@ jobs: with: node-version: ${{ matrix.node-version }} - run: npm i + - run: npm run lint - run: npm test
1
Merge pull request #255 from abetomo/feature/add_lint_to_ci
0
.yml
github/workflows/workflow
apache-2.0
dwyl/aws-sdk-mock
546
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> When remock is called, update all instances of client <DFF> @@ -121,9 +121,6 @@ function mockService(service) { * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { - if (client[method] && typeof client[method].restore === 'function') { - client[method].restore(); - } services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments);
0
When remock is called, update all instances of client
3
.js
js
apache-2.0
dwyl/aws-sdk-mock
547
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> When remock is called, update all instances of client <DFF> @@ -121,9 +121,6 @@ function mockService(service) { * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { - if (client[method] && typeof client[method].restore === 'function') { - client[method].restore(); - } services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments);
0
When remock is called, update all instances of client
3
.js
js
apache-2.0
dwyl/aws-sdk-mock
548
<NME> index.test-d.ts <BEF> import * as AWS from 'aws-sdk'; import { AWSError } from 'aws-sdk'; import { ListObjectsV2Request } from 'aws-sdk/clients/s3'; import { expectError, expectType } from 'tsd'; import { mock, remock, restore, setSDK, setSDKInstance } from '../index'; const awsError: AWSError = { name: 'AWSError', message: 'message', code: 'code', time: new Date(), }; expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); const output: AWS.S3.ListObjectsV2Output = { Name: params.Bucket, MaxKeys: params.MaxKeys, Delimiter: params.Delimiter, Prefix: params.Prefix, KeyCount: 1, IsTruncated: false, ContinuationToken: params.ContinuationToken, Contents: [ { LastModified: new Date(), ETag: '"668d791b0c7d6a7f0f86c269888b4546"', StorageClass: 'STANDARD', Key: 'aws-sdk-mock/index.js', Size: 8524, }, ] }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectError(mock('S3', 'describeObjects', (params, callback) => { expectType<never>(params); expectType<never>(callback); })); expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen')); expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen')); expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen')); expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen')); expectError(mock('StaticDB', 'getItem', "it couldn't")); expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { // $ExpectType string[] const instanceIds = params.InstanceIds; expectType<string[]>(instanceIds); const output: AWS.EC2.StopInstancesResult = { StoppingInstances: instanceIds.map(id => ({ InstanceId: id, PreviousState: { Name: 'running' }, CurrentState: { Name: 'stopping' }, })), }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectType<void>(remock('Snowball', 'makeRequest', undefined)); expectError(remock('Snowball', 'throwRequest', undefined)); expectType<void>(restore('Pricing', 'getProducts')); expectError(restore('Pricing', 'borrowMoney')); expectType<void>(restore('KMS')); expectError(restore('Skynet')); expectError(restore(42)); expectType<void>(restore()); expectError(restore(null)); expectType<void>(setSDK('aws-sdk')); expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk'))); async function foo() { expectType<void>(setSDKInstance(await import('aws-sdk'))); } expectError(setSDKInstance(AWS.S3)); import allClients = require('aws-sdk/clients/all'); expectError(setSDKInstance(allClients)); <MSG> Merge branch 'main' of github.com:dwyl/aws-sdk-mock <DFF> @@ -11,6 +11,9 @@ const awsError: AWSError = { time: new Date(), }; +/** + * mock + */ expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); @@ -83,16 +86,30 @@ expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { expectError(callback(awsError, output)); })); +/** + * Remock + */ expectType<void>(remock('Snowball', 'makeRequest', undefined)); +expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined)); + expectError(remock('Snowball', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentServer', 'get', undefined)); +/** + * Restore + */ expectType<void>(restore('Pricing', 'getProducts')); +expectType<void>(restore('DynamoDB.DocumentClient', 'get')); expectError(restore('Pricing', 'borrowMoney')); +expectError(restore('DynamoDB.DocumentClient', 'unknown')); expectType<void>(restore('KMS')); +expectType<void>(restore('DynamoDB.DocumentClient')); expectError(restore('Skynet')); +expectError(restore('DynamoDB.DocumentServer')); expectError(restore(42)); @@ -100,8 +117,14 @@ expectType<void>(restore()); expectError(restore(null)); +/** + * setSDK + */ expectType<void>(setSDK('aws-sdk')); +/** + * setSDKInstance + */ expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk')));
23
Merge branch 'main' of github.com:dwyl/aws-sdk-mock
0
.ts
test-d
apache-2.0
dwyl/aws-sdk-mock
549
<NME> index.test-d.ts <BEF> import * as AWS from 'aws-sdk'; import { AWSError } from 'aws-sdk'; import { ListObjectsV2Request } from 'aws-sdk/clients/s3'; import { expectError, expectType } from 'tsd'; import { mock, remock, restore, setSDK, setSDKInstance } from '../index'; const awsError: AWSError = { name: 'AWSError', message: 'message', code: 'code', time: new Date(), }; expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); const output: AWS.S3.ListObjectsV2Output = { Name: params.Bucket, MaxKeys: params.MaxKeys, Delimiter: params.Delimiter, Prefix: params.Prefix, KeyCount: 1, IsTruncated: false, ContinuationToken: params.ContinuationToken, Contents: [ { LastModified: new Date(), ETag: '"668d791b0c7d6a7f0f86c269888b4546"', StorageClass: 'STANDARD', Key: 'aws-sdk-mock/index.js', Size: 8524, }, ] }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectError(mock('S3', 'describeObjects', (params, callback) => { expectType<never>(params); expectType<never>(callback); })); expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen')); expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen')); expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen')); expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen')); expectError(mock('StaticDB', 'getItem', "it couldn't")); expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { // $ExpectType string[] const instanceIds = params.InstanceIds; expectType<string[]>(instanceIds); const output: AWS.EC2.StopInstancesResult = { StoppingInstances: instanceIds.map(id => ({ InstanceId: id, PreviousState: { Name: 'running' }, CurrentState: { Name: 'stopping' }, })), }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectType<void>(remock('Snowball', 'makeRequest', undefined)); expectError(remock('Snowball', 'throwRequest', undefined)); expectType<void>(restore('Pricing', 'getProducts')); expectError(restore('Pricing', 'borrowMoney')); expectType<void>(restore('KMS')); expectError(restore('Skynet')); expectError(restore(42)); expectType<void>(restore()); expectError(restore(null)); expectType<void>(setSDK('aws-sdk')); expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk'))); async function foo() { expectType<void>(setSDKInstance(await import('aws-sdk'))); } expectError(setSDKInstance(AWS.S3)); import allClients = require('aws-sdk/clients/all'); expectError(setSDKInstance(allClients)); <MSG> Merge branch 'main' of github.com:dwyl/aws-sdk-mock <DFF> @@ -11,6 +11,9 @@ const awsError: AWSError = { time: new Date(), }; +/** + * mock + */ expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); @@ -83,16 +86,30 @@ expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { expectError(callback(awsError, output)); })); +/** + * Remock + */ expectType<void>(remock('Snowball', 'makeRequest', undefined)); +expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined)); + expectError(remock('Snowball', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentServer', 'get', undefined)); +/** + * Restore + */ expectType<void>(restore('Pricing', 'getProducts')); +expectType<void>(restore('DynamoDB.DocumentClient', 'get')); expectError(restore('Pricing', 'borrowMoney')); +expectError(restore('DynamoDB.DocumentClient', 'unknown')); expectType<void>(restore('KMS')); +expectType<void>(restore('DynamoDB.DocumentClient')); expectError(restore('Skynet')); +expectError(restore('DynamoDB.DocumentServer')); expectError(restore(42)); @@ -100,8 +117,14 @@ expectType<void>(restore()); expectError(restore(null)); +/** + * setSDK + */ expectType<void>(setSDK('aws-sdk')); +/** + * setSDKInstance + */ expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk')));
23
Merge branch 'main' of github.com:dwyl/aws-sdk-mock
0
.ts
test-d
apache-2.0
dwyl/aws-sdk-mock
550
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; } /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Merge pull request #8 from dwyl/remove-bitwise-operator Removed bitwise operator for more readability <DFF> @@ -32,7 +32,7 @@ AWS.mock = function(service, method, replace) { services[service].methodMocks = [] mockService(service, method, replace); } else { - var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; + var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; }
1
Merge pull request #8 from dwyl/remove-bitwise-operator
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
551
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; } /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Merge pull request #8 from dwyl/remove-bitwise-operator Removed bitwise operator for more readability <DFF> @@ -32,7 +32,7 @@ AWS.mock = function(service, method, replace) { services[service].methodMocks = [] mockService(service, method, replace); } else { - var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; + var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; }
1
Merge pull request #8 from dwyl/remove-bitwise-operator
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
552
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://travis-ci.org/dwyl/aws-sdk-mock.svg?branch=master)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://codecov.io/github/dwyl/aws-sdk-mock/coverage.svg?branch=master)](https://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> add snyk dependency checking and badge in README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161 <DFF> @@ -2,10 +2,11 @@ AWSome mocks for Javascript aws-sdk services. -[![Build Status](https://travis-ci.org/dwyl/aws-sdk-mock.svg?branch=master)](https://travis-ci.org/dwyl/aws-sdk-mock) -[![codecov.io](https://codecov.io/github/dwyl/aws-sdk-mock/coverage.svg?branch=master)](https://codecov.io/github/dwyl/aws-sdk-mock?branch=master) -[![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg)](https://david-dm.org/dwyl/aws-sdk-mock) -[![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) +[![Build Status](https://travis-ci.org/dwyl/aws-sdk-mock.svg?branch=master&style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) +[![codecov.io](https://codecov.io/github/dwyl/aws-sdk-mock/coverage.svg?branch=master&style=flat-square)](https://codecov.io/github/dwyl/aws-sdk-mock?branch=master) +[![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) +[![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) +[![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/)
5
add snyk dependency checking and badge in README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161
4
.md
md
apache-2.0
dwyl/aws-sdk-mock
553
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://travis-ci.org/dwyl/aws-sdk-mock.svg?branch=master)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://codecov.io/github/dwyl/aws-sdk-mock/coverage.svg?branch=master)](https://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> add snyk dependency checking and badge in README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161 <DFF> @@ -2,10 +2,11 @@ AWSome mocks for Javascript aws-sdk services. -[![Build Status](https://travis-ci.org/dwyl/aws-sdk-mock.svg?branch=master)](https://travis-ci.org/dwyl/aws-sdk-mock) -[![codecov.io](https://codecov.io/github/dwyl/aws-sdk-mock/coverage.svg?branch=master)](https://codecov.io/github/dwyl/aws-sdk-mock?branch=master) -[![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg)](https://david-dm.org/dwyl/aws-sdk-mock) -[![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) +[![Build Status](https://travis-ci.org/dwyl/aws-sdk-mock.svg?branch=master&style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) +[![codecov.io](https://codecov.io/github/dwyl/aws-sdk-mock/coverage.svg?branch=master&style=flat-square)](https://codecov.io/github/dwyl/aws-sdk-mock?branch=master) +[![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) +[![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) +[![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/)
5
add snyk dependency checking and badge in README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161
4
.md
md
apache-2.0
dwyl/aws-sdk-mock
554
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); st.end(); }); }); t.test('service is re-mocked if update flag passed', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }, true); sns.subscribe({}, function(err, data){ st.equals(data, 'message 2'); st.end(); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> add remock function, remove update <DFF> @@ -98,14 +98,14 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('service is re-mocked if update flag passed', function(st){ + t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); var sns = new AWS.SNS(); - awsMock.mock('SNS', 'subscribe', function(params, callback){ + awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); - }, true); + }); sns.subscribe({}, function(err, data){ st.equals(data, 'message 2'); st.end();
3
add remock function, remove update
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
555
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); st.end(); }); }); t.test('service is re-mocked if update flag passed', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }, true); sns.subscribe({}, function(err, data){ st.equals(data, 'message 2'); st.end(); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> add remock function, remove update <DFF> @@ -98,14 +98,14 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('service is re-mocked if update flag passed', function(st){ + t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); var sns = new AWS.SNS(); - awsMock.mock('SNS', 'subscribe', function(params, callback){ + awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); - }, true); + }); sns.subscribe({}, function(err, data){ st.equals(data, 'message 2'); st.end();
3
add remock function, remove update
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
556
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); }); st.end(); }) t.end(); }); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge branch 'master' into patch-1 # Conflicts: # package.json <DFF> @@ -277,5 +277,33 @@ test('AWS.mock function should mock AWS service and method on the service', func }); st.end(); }) + t.test('Mocked service should return the sinon stub', function(st) { + var stub = awsMock.mock('CloudSearchDomain', 'search'); + st.equals(stub.stub.isSinonProxy, true); + st.end(); + }); + t.end(); +}); + +test('AWS.setSDK function should mock a specific AWS module', function(t) { + t.test('Specific Modules can be set for mocking', function(st) { + awsMock.setSDK('aws-sdk'); + awsMock.mock('SNS', 'publish', 'message'); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }); + + t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { + awsMock.setSDK('sinon'); + st.throws(function() { + awsMock.mock('SNS', 'publish', 'message') + }); + awsMock.setSDK('aws-sdk'); + st.end(); + }); t.end(); });
28
Merge branch 'master' into patch-1
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
557
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); }); st.end(); }) t.end(); }); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge branch 'master' into patch-1 # Conflicts: # package.json <DFF> @@ -277,5 +277,33 @@ test('AWS.mock function should mock AWS service and method on the service', func }); st.end(); }) + t.test('Mocked service should return the sinon stub', function(st) { + var stub = awsMock.mock('CloudSearchDomain', 'search'); + st.equals(stub.stub.isSinonProxy, true); + st.end(); + }); + t.end(); +}); + +test('AWS.setSDK function should mock a specific AWS module', function(t) { + t.test('Specific Modules can be set for mocking', function(st) { + awsMock.setSDK('aws-sdk'); + awsMock.mock('SNS', 'publish', 'message'); + var sns = new AWS.SNS(); + sns.publish({}, function(err, data){ + st.equals(data, 'message'); + awsMock.restore('SNS'); + st.end(); + }) + }); + + t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { + awsMock.setSDK('sinon'); + st.throws(function() { + awsMock.mock('SNS', 'publish', 'message') + }); + awsMock.setSDK('aws-sdk'); + st.end(); + }); t.end(); });
28
Merge branch 'master' into patch-1
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
558
<NME> index.d.ts <BEF> declare module 'aws-sdk-mock' { function mock(service: string, method: string, replace: string): void; function mock( service: string, replace: (params: any, callback: (err: any, data: any) => void) => void ): void; function remock(service: string, method: string, replace: string): void; function remock( service: string, method: string, replace: (params: any, callback: (err: any, data: any) => void) => void ): void; function restore(service: string): void; function restore(service: string, method: string): void; function setSDK(path: string): void; function setSDKInstance(instance: object): void; } export type Callback<D> = (err: AWSError | undefined, data: D) => void; export type ReplaceFn<C extends ClientName, M extends MethodName<C>> = (params: AWSRequest<C, M>, callback: AWSCallback<C, M>) => void export function mock<C extends ClientName, M extends MethodName<C>>( service: C, method: M, replace: ReplaceFn<C, M>, ): void; export function mock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void; export function mock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void; export function remock<C extends ClientName, M extends MethodName<C>>( service: C, method: M, replace: ReplaceFn<C, M>, ): void; export function remock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void; export function remock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void; export function restore<C extends ClientName>(service?: C, method?: MethodName<C>): void; export function restore<C extends ClientName, NC extends NestedClientName<C>>(service?: NestedClientFullName<C, NC>, method?: NestedMethodName<C, NC>): void; export function setSDK(path: string): void; export function setSDKInstance(instance: typeof import('aws-sdk')): void; /** * The SDK defines a class for each service as well as a namespace with the same name. * Nested clients, e.g. DynamoDB.DocumentClient, are defined on the namespace, not the class. * That is why we need to fetch these separately as defined below in the NestedClientName<C> type * * The NestedClientFullName type supports validating strings representing a nested clients name in dot notation * * We add the ts-ignore comments to avoid the type system to trip over the many possible values for NestedClientName<C> */ export type NestedClientName<C extends ClientName> = keyof typeof AWS[C]; // @ts-ignore export type NestedClientFullName<C extends ClientName, NC extends NestedClientName<C>> = `${C}.${NC}`; // @ts-ignore export type NestedClient<C extends ClientName, NC extends NestedClientName<C>> = InstanceType<(typeof AWS)[C][NC]>; // @ts-ignore export type NestedMethodName<C extends ClientName, NC extends NestedClientName<C>> = keyof ExtractMethod<NestedClient<C, NC>>; <MSG> Merge pull request #172 from joostfarla/ts Fix wrong TypeScript definitions <DFF> @@ -1,5 +1,5 @@ declare module 'aws-sdk-mock' { - function mock(service: string, method: string, replace: string): void; + function mock(service: string, method: string, replace: any): void; function mock( service: string, @@ -7,15 +7,14 @@ declare module 'aws-sdk-mock' { replace: (params: any, callback: (err: any, data: any) => void) => void ): void; - function remock(service: string, method: string, replace: string): void; + function remock(service: string, method: string, replace: any): void; function remock( service: string, method: string, replace: (params: any, callback: (err: any, data: any) => void) => void ): void; - function restore(service: string): void; - function restore(service: string, method: string): void; + function restore(service?: string, method?: string): void; function setSDK(path: string): void; function setSDKInstance(instance: object): void;
3
Merge pull request #172 from joostfarla/ts
4
.ts
d
apache-2.0
dwyl/aws-sdk-mock
559
<NME> index.d.ts <BEF> declare module 'aws-sdk-mock' { function mock(service: string, method: string, replace: string): void; function mock( service: string, replace: (params: any, callback: (err: any, data: any) => void) => void ): void; function remock(service: string, method: string, replace: string): void; function remock( service: string, method: string, replace: (params: any, callback: (err: any, data: any) => void) => void ): void; function restore(service: string): void; function restore(service: string, method: string): void; function setSDK(path: string): void; function setSDKInstance(instance: object): void; } export type Callback<D> = (err: AWSError | undefined, data: D) => void; export type ReplaceFn<C extends ClientName, M extends MethodName<C>> = (params: AWSRequest<C, M>, callback: AWSCallback<C, M>) => void export function mock<C extends ClientName, M extends MethodName<C>>( service: C, method: M, replace: ReplaceFn<C, M>, ): void; export function mock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void; export function mock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void; export function remock<C extends ClientName, M extends MethodName<C>>( service: C, method: M, replace: ReplaceFn<C, M>, ): void; export function remock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void; export function remock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void; export function restore<C extends ClientName>(service?: C, method?: MethodName<C>): void; export function restore<C extends ClientName, NC extends NestedClientName<C>>(service?: NestedClientFullName<C, NC>, method?: NestedMethodName<C, NC>): void; export function setSDK(path: string): void; export function setSDKInstance(instance: typeof import('aws-sdk')): void; /** * The SDK defines a class for each service as well as a namespace with the same name. * Nested clients, e.g. DynamoDB.DocumentClient, are defined on the namespace, not the class. * That is why we need to fetch these separately as defined below in the NestedClientName<C> type * * The NestedClientFullName type supports validating strings representing a nested clients name in dot notation * * We add the ts-ignore comments to avoid the type system to trip over the many possible values for NestedClientName<C> */ export type NestedClientName<C extends ClientName> = keyof typeof AWS[C]; // @ts-ignore export type NestedClientFullName<C extends ClientName, NC extends NestedClientName<C>> = `${C}.${NC}`; // @ts-ignore export type NestedClient<C extends ClientName, NC extends NestedClientName<C>> = InstanceType<(typeof AWS)[C][NC]>; // @ts-ignore export type NestedMethodName<C extends ClientName, NC extends NestedClientName<C>> = keyof ExtractMethod<NestedClient<C, NC>>; <MSG> Merge pull request #172 from joostfarla/ts Fix wrong TypeScript definitions <DFF> @@ -1,5 +1,5 @@ declare module 'aws-sdk-mock' { - function mock(service: string, method: string, replace: string): void; + function mock(service: string, method: string, replace: any): void; function mock( service: string, @@ -7,15 +7,14 @@ declare module 'aws-sdk-mock' { replace: (params: any, callback: (err: any, data: any) => void) => void ): void; - function remock(service: string, method: string, replace: string): void; + function remock(service: string, method: string, replace: any): void; function remock( service: string, method: string, replace: (params: any, callback: (err: any, data: any) => void) => void ): void; - function restore(service: string): void; - function restore(service: string, method: string): void; + function restore(service?: string, method?: string): void; function setSDK(path: string): void; function setSDKInstance(instance: object): void;
3
Merge pull request #172 from joostfarla/ts
4
.ts
d
apache-2.0
dwyl/aws-sdk-mock
560
<NME> index.test.js <BEF> var tap = require('tap'); var test = tap.test; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "test"); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); }); sns.publish({}, function(err, data){ }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, "test"); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); st.equals(AWS.SNS.isSinonProxy, true); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, "test"); }); var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB(); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Check test code with eslint Fix test code according to rules <DFF> @@ -1,7 +1,7 @@ -var tap = require('tap'); -var test = tap.test; +var tap = require('tap'); +var test = tap.test; var awsMock = require('../index.js'); -var AWS = require('aws-sdk'); +var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; @@ -24,7 +24,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ @@ -74,11 +74,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); @@ -87,11 +87,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); @@ -299,7 +299,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); st.equals(AWS.SNS.isSinonProxy, true); @@ -310,7 +310,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); @@ -324,15 +324,15 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); - var sns = new AWS.SNS(); + var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB();
14
Check test code with eslint
14
.js
test
apache-2.0
dwyl/aws-sdk-mock
561
<NME> index.test.js <BEF> var tap = require('tap'); var test = tap.test; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "test"); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); }); sns.publish({}, function(err, data){ }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, "test"); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); st.equals(AWS.SNS.isSinonProxy, true); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, "test"); }); var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB(); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Check test code with eslint Fix test code according to rules <DFF> @@ -1,7 +1,7 @@ -var tap = require('tap'); -var test = tap.test; +var tap = require('tap'); +var test = tap.test; var awsMock = require('../index.js'); -var AWS = require('aws-sdk'); +var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; @@ -24,7 +24,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ @@ -74,11 +74,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); @@ -87,11 +87,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); @@ -299,7 +299,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); st.equals(AWS.SNS.isSinonProxy, true); @@ -310,7 +310,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); @@ -324,15 +324,15 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); - var sns = new AWS.SNS(); + var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB();
14
Check test code with eslint
14
.js
test
apache-2.0
dwyl/aws-sdk-mock
562
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise if(typeof(AWS.Promise) === 'function' && typeof(args[args.length - 1]) !== 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) { const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Update index.js <DFF> @@ -87,7 +87,7 @@ function mockServiceMethod(service, client, method, replace) { var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise - if(typeof(AWS.Promise) === 'function' && typeof(args[args.length - 1]) !== 'function') { + if(typeof(args[args.length - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) {
1
Update index.js
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
563
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise if(typeof(AWS.Promise) === 'function' && typeof(args[args.length - 1]) !== 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) { const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Update index.js <DFF> @@ -87,7 +87,7 @@ function mockServiceMethod(service, client, method, replace) { var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise - if(typeof(AWS.Promise) === 'function' && typeof(args[args.length - 1]) !== 'function') { + if(typeof(args[args.length - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) {
1
Update index.js
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
564
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> comment out NPM download stats badge from README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 <DFF> @@ -8,7 +8,9 @@ AWSome mocks for Javascript aws-sdk services. [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) +<!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) +--> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked.
2
comment out NPM download stats badge from README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
565
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> comment out NPM download stats badge from README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 <DFF> @@ -8,7 +8,9 @@ AWSome mocks for Javascript aws-sdk services. [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) +<!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) +--> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked.
2
comment out NPM download stats badge from README.md see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
566
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. ## What? Uses Sinon.js under the hood to mock the AWS SDK services and associated methods. ## *How*? (*Usage*) Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ```js import AWS from 'aws-sdk-mock'; AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); }); AWS.mock('SNS', 'publish'); /** TESTS AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` ## Documentation done(); }); Replaces a method on an AWS service with a replacement function or string. - `service`: AWS service to mock e.g. SNS, DynamoDB, S3 - `method` : method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' - `replace` : a string or function to replace the method ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service Optional: - `service` : AWS service to restore - If only the service is specified, all the methods are restored - `method` : Method on AWS service to restore If no arguments are given to `AWS.restore` then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ## Background Reading const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Adds more information to readme on implementation <DFF> @@ -9,6 +9,8 @@ AWSome mocks for Javascript aws-sdk services. [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) +This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. + If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our @@ -19,11 +21,11 @@ https://github.com/dwyl/learn-aws-lambda Testing your code is *essential* everywhere you need *reliability*. -Using stubs means you can prevent a specific method from being called directly. +Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? -Uses Sinon.js under the hood to mock the AWS SDK services and associated methods. +Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) @@ -37,13 +39,13 @@ npm install aws-sdk-mock --save-dev ```js -import AWS from 'aws-sdk-mock'; +var AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); }); -AWS.mock('SNS', 'publish'); +AWS.mock('SNS', 'publish', 'test-message'); /** TESTS @@ -51,7 +53,31 @@ AWS.mock('SNS', 'publish'); AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); -// or AWS.restore(); this will restore all the methods and services +// or AWS.restore(); this will restore all the methods and services +``` + +**NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. + +Example 1: +```js +var AWS = require('aws-sdk'); +var sns = AWS.SNS(); +var dynamoDb = AWS.DynamoDB(); + +exports.handler = function(event, context) { + // do something with the services e.g. sns.publish +} +``` + +Example 2: +```js +var AWS = require('aws-sdk'); + +exports.handler = function(event, context) { + var sns = AWS.SNS(); + var dynamoDb = AWS.DynamoDB(); + // do something with the services e.g. sns.publish +} ``` ## Documentation @@ -60,20 +86,29 @@ AWS.restore('DynamoDB'); Replaces a method on an AWS service with a replacement function or string. -- `service`: AWS service to mock e.g. SNS, DynamoDB, S3 -- `method` : method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' -- `replace` : a string or function to replace the method + +| Param | Type | Optional/Required | Description | +| :------------- | :------------- | :------------- | :------------- | +| `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | +| `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | +| `replace` | string or function | Required | A string or function to replace the method | + ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service -Optional: -- `service` : AWS service to restore - If only the service is specified, all the methods are restored -- `method` : Method on AWS service to restore +| Param | Type | Optional/Required | Description | +| :------------- | :------------- | :------------- | :------------- | +| `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | +| `method` | string | Optional | Method on AWS service to restore | -If no arguments are given to `AWS.restore` then all the services and their associated methods are restored +If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. - ## Background Reading + +* (Mocking using Sinon.js)[http://sinonjs.org/docs/] +* (AWS Lambda)[https://github.com/dwyl/learn-aws-lambda] + +**Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving**
48
Adds more information to readme on implementation
13
.md
md
apache-2.0
dwyl/aws-sdk-mock
567
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. ## What? Uses Sinon.js under the hood to mock the AWS SDK services and associated methods. ## *How*? (*Usage*) Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ```js import AWS from 'aws-sdk-mock'; AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); }); AWS.mock('SNS', 'publish'); /** TESTS AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` ## Documentation done(); }); Replaces a method on an AWS service with a replacement function or string. - `service`: AWS service to mock e.g. SNS, DynamoDB, S3 - `method` : method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' - `replace` : a string or function to replace the method ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service Optional: - `service` : AWS service to restore - If only the service is specified, all the methods are restored - `method` : Method on AWS service to restore If no arguments are given to `AWS.restore` then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ## Background Reading const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Adds more information to readme on implementation <DFF> @@ -9,6 +9,8 @@ AWSome mocks for Javascript aws-sdk services. [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) +This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. + If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our @@ -19,11 +21,11 @@ https://github.com/dwyl/learn-aws-lambda Testing your code is *essential* everywhere you need *reliability*. -Using stubs means you can prevent a specific method from being called directly. +Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? -Uses Sinon.js under the hood to mock the AWS SDK services and associated methods. +Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) @@ -37,13 +39,13 @@ npm install aws-sdk-mock --save-dev ```js -import AWS from 'aws-sdk-mock'; +var AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); }); -AWS.mock('SNS', 'publish'); +AWS.mock('SNS', 'publish', 'test-message'); /** TESTS @@ -51,7 +53,31 @@ AWS.mock('SNS', 'publish'); AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); -// or AWS.restore(); this will restore all the methods and services +// or AWS.restore(); this will restore all the methods and services +``` + +**NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. + +Example 1: +```js +var AWS = require('aws-sdk'); +var sns = AWS.SNS(); +var dynamoDb = AWS.DynamoDB(); + +exports.handler = function(event, context) { + // do something with the services e.g. sns.publish +} +``` + +Example 2: +```js +var AWS = require('aws-sdk'); + +exports.handler = function(event, context) { + var sns = AWS.SNS(); + var dynamoDb = AWS.DynamoDB(); + // do something with the services e.g. sns.publish +} ``` ## Documentation @@ -60,20 +86,29 @@ AWS.restore('DynamoDB'); Replaces a method on an AWS service with a replacement function or string. -- `service`: AWS service to mock e.g. SNS, DynamoDB, S3 -- `method` : method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' -- `replace` : a string or function to replace the method + +| Param | Type | Optional/Required | Description | +| :------------- | :------------- | :------------- | :------------- | +| `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | +| `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | +| `replace` | string or function | Required | A string or function to replace the method | + ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service -Optional: -- `service` : AWS service to restore - If only the service is specified, all the methods are restored -- `method` : Method on AWS service to restore +| Param | Type | Optional/Required | Description | +| :------------- | :------------- | :------------- | :------------- | +| `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | +| `method` | string | Optional | Method on AWS service to restore | -If no arguments are given to `AWS.restore` then all the services and their associated methods are restored +If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. - ## Background Reading + +* (Mocking using Sinon.js)[http://sinonjs.org/docs/] +* (AWS Lambda)[https://github.com/dwyl/learn-aws-lambda] + +**Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving**
48
Adds more information to readme on implementation
13
.md
md
apache-2.0
dwyl/aws-sdk-mock
568
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ``` AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ``` // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> edit README.md * edit a typing error * add syntax highlightings <DFF> @@ -53,7 +53,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); -// S3 getObject mock - return a Bffer object with file data +// S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); @@ -116,7 +116,7 @@ exports.handler = function(event, context) { It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: -``` +```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); @@ -124,7 +124,7 @@ AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: -``` +```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message');
3
edit README.md
3
.md
md
apache-2.0
dwyl/aws-sdk-mock
569
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ``` AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ``` // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> edit README.md * edit a typing error * add syntax highlightings <DFF> @@ -53,7 +53,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); -// S3 getObject mock - return a Bffer object with file data +// S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); @@ -116,7 +116,7 @@ exports.handler = function(event, context) { It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: -``` +```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); @@ -124,7 +124,7 @@ AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: -``` +```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message');
3
edit README.md
3
.md
md
apache-2.0
dwyl/aws-sdk-mock
570
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true}); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); }); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #55 from eduponte/master fix(paramValidation): skip param validation when method has no input rules <DFF> @@ -52,6 +52,15 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { + awsMock.mock('S3', 'getSignedUrl', 'message'); + var s3 = new AWS.S3({paramValidation: true}); + s3.getSignedUrl('getObject', {}, function(err, data) { + st.equals(data, 'message'); + awsMock.restore('S3'); + st.end(); + }); + }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true}); @@ -318,6 +327,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }) }); + t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ + awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { + callback(null, 'test'); + }); + var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.query.isSinonProxy, true); + docClient.query({}, function(err, data){ + console.warn(err); + st.equals(data, 'test'); + awsMock.restore('DynamoDB.DocumentClient', 'query'); + st.end(); + }) + }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test');
24
Merge pull request #55 from eduponte/master
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
571
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true}); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); }); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #55 from eduponte/master fix(paramValidation): skip param validation when method has no input rules <DFF> @@ -52,6 +52,15 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { + awsMock.mock('S3', 'getSignedUrl', 'message'); + var s3 = new AWS.S3({paramValidation: true}); + s3.getSignedUrl('getObject', {}, function(err, data) { + st.equals(data, 'message'); + awsMock.restore('S3'); + st.end(); + }); + }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true}); @@ -318,6 +327,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }) }); + t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ + awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { + callback(null, 'test'); + }); + var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.query.isSinonProxy, true); + docClient.query({}, function(err, data){ + console.warn(err); + st.equals(data, 'test'); + awsMock.restore('DynamoDB.DocumentClient', 'query'); + st.end(); + }) + }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test');
24
Merge pull request #55 from eduponte/master
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
572
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "8" - "10" - "12" before_install: - pip install --user codecov after_success: <MSG> Add Node.js 14 to ci settings <DFF> @@ -4,6 +4,7 @@ node_js: - "8" - "10" - "12" + - "14" before_install: - pip install --user codecov after_success:
1
Add Node.js 14 to ci settings
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
573
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "8" - "10" - "12" before_install: - pip install --user codecov after_success: <MSG> Add Node.js 14 to ci settings <DFF> @@ -4,6 +4,7 @@ node_js: - "8" - "10" - "12" + - "14" before_install: - pip install --user codecov after_success:
1
Add Node.js 14 to ci settings
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
574
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ mockServiceMethod(service, services[service].client, method, replace); } } return services[service].methodMocks[method]; } /** // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Save this for future PR <DFF> @@ -44,7 +44,6 @@ AWS.mock = function(service, method, replace) { mockServiceMethod(service, services[service].client, method, replace); } } - return services[service].methodMocks[method]; } /**
0
Save this for future PR
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
575
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ mockServiceMethod(service, services[service].client, method, replace); } } return services[service].methodMocks[method]; } /** // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Save this for future PR <DFF> @@ -44,7 +44,6 @@ AWS.mock = function(service, method, replace) { mockServiceMethod(service, services[service].client, method, replace); } } - return services[service].methodMocks[method]; } /**
0
Save this for future PR
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
576
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); st.end(); }); }); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); }); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge branch 'master' into master <DFF> @@ -48,6 +48,16 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); + awsMock.restore('S3', 'getObject'); + st.end(); + }); + }); + t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { + awsMock.mock('S3', 'getSignedUrl', 'message'); + var s3 = new AWS.S3({paramValidation: true}); + s3.getSignedUrl('getObject', {}, function(err, data) { + st.equals(data, 'message'); + awsMock.restore('S3'); st.end(); }); }); @@ -57,6 +67,7 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); + awsMock.restore('S3', 'getObject'); st.end(); }); }); @@ -181,6 +192,51 @@ test('AWS.mock function should mock AWS service and method on the service', func req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream works with strings', function(st) { + awsMock.mock('S3', 'getObject', 'body'); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body') + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream works with buffers', function(st) { + awsMock.mock('S3', 'getObject', new Buffer('body')); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body') + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream ignores functions', function(st) { + awsMock.mock('S3', 'getObject', function(){}); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), '') + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream ignores non-buffer objects', function(st) { + awsMock.mock('S3', 'getObject', {Body: 'body'}); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), '') + awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -271,6 +327,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }) }); + t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ + awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { + callback(null, 'test'); + }); + var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.query.isSinonProxy, true); + docClient.query({}, function(err, data){ + console.warn(err); + st.equals(data, 'test'); + awsMock.restore('DynamoDB.DocumentClient', 'query'); + st.end(); + }) + }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test');
71
Merge branch 'master' into master
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
577
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); st.end(); }); }); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); }); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge branch 'master' into master <DFF> @@ -48,6 +48,16 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); + awsMock.restore('S3', 'getObject'); + st.end(); + }); + }); + t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { + awsMock.mock('S3', 'getSignedUrl', 'message'); + var s3 = new AWS.S3({paramValidation: true}); + s3.getSignedUrl('getObject', {}, function(err, data) { + st.equals(data, 'message'); + awsMock.restore('S3'); st.end(); }); }); @@ -57,6 +67,7 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); + awsMock.restore('S3', 'getObject'); st.end(); }); }); @@ -181,6 +192,51 @@ test('AWS.mock function should mock AWS service and method on the service', func req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream works with strings', function(st) { + awsMock.mock('S3', 'getObject', 'body'); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body') + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream works with buffers', function(st) { + awsMock.mock('S3', 'getObject', new Buffer('body')); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body') + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream ignores functions', function(st) { + awsMock.mock('S3', 'getObject', function(){}); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), '') + awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream ignores non-buffer objects', function(st) { + awsMock.mock('S3', 'getObject', {Body: 'body'}); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), '') + awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -271,6 +327,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }) }); + t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ + awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { + callback(null, 'test'); + }); + var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.query.isSinonProxy, true); + docClient.query({}, function(err, data){ + console.warn(err); + st.equals(data, 'test'); + awsMock.restore('DynamoDB.DocumentClient', 'query'); + st.end(); + }) + }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test');
71
Merge branch 'master' into master
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
578
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ mockServiceMethod(service, services[service].client, method, replace); } } } /** if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise if(typeof(args[args.length - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) { // Provide a callback function for the mock to invoke args.push(function(err, val) { return err ? reject(err) : resolve(val) }) return invokeMock() }) } } } return invokeMock() function invokeMock() { // If the value of 'replace' is a function we call it with the arguments. if(typeof(replace) === 'function') { for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Handle AWS method being called w/o arguments <DFF> @@ -44,6 +44,7 @@ AWS.mock = function(service, method, replace) { mockServiceMethod(service, services[service].client, method, replace); } } + return services[service].methodMocks[method]; } /** @@ -87,20 +88,20 @@ function mockServiceMethod(service, client, method, replace) { var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise - if(typeof(args[args.length - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { + if(typeof(args[(args.length || 1) - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) { // Provide a callback function for the mock to invoke args.push(function(err, val) { return err ? reject(err) : resolve(val) }) - return invokeMock() + return invokeMock(); }) } } + } else { + return invokeMock(); } - return invokeMock() - function invokeMock() { // If the value of 'replace' is a function we call it with the arguments. if(typeof(replace) === 'function') {
5
Handle AWS method being called w/o arguments
4
.js
js
apache-2.0
dwyl/aws-sdk-mock
579
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ mockServiceMethod(service, services[service].client, method, replace); } } } /** if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise if(typeof(args[args.length - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) { // Provide a callback function for the mock to invoke args.push(function(err, val) { return err ? reject(err) : resolve(val) }) return invokeMock() }) } } } return invokeMock() function invokeMock() { // If the value of 'replace' is a function we call it with the arguments. if(typeof(replace) === 'function') { for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Handle AWS method being called w/o arguments <DFF> @@ -44,6 +44,7 @@ AWS.mock = function(service, method, replace) { mockServiceMethod(service, services[service].client, method, replace); } } + return services[service].methodMocks[method]; } /** @@ -87,20 +88,20 @@ function mockServiceMethod(service, client, method, replace) { var args = Array.prototype.slice.call(arguments); // If the method was called w/o a callback function, assume they are consuming a Promise - if(typeof(args[args.length - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { + if(typeof(args[(args.length || 1) - 1]) !== 'function' && typeof(AWS.Promise) === 'function') { return { promise: function() { return new AWS.Promise(function(resolve, reject) { // Provide a callback function for the mock to invoke args.push(function(err, val) { return err ? reject(err) : resolve(val) }) - return invokeMock() + return invokeMock(); }) } } + } else { + return invokeMock(); } - return invokeMock() - function invokeMock() { // If the value of 'replace' is a function we call it with the arguments. if(typeof(replace) === 'function') {
5
Handle AWS method being called w/o arguments
4
.js
js
apache-2.0
dwyl/aws-sdk-mock
580
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #117 from nagapavan/patch-1 Update README.md <DFF> @@ -53,12 +53,16 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); +// S3 getObject mock - return a Bffer object with file data +awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); + /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); +AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ```
4
Merge pull request #117 from nagapavan/patch-1
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
581
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #117 from nagapavan/patch-1 Update README.md <DFF> @@ -53,12 +53,16 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); +// S3 getObject mock - return a Bffer object with file data +awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); + /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); +AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ```
4
Merge pull request #117 from nagapavan/patch-1
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
582
<NME> index.test.js <BEF> var tap = require('tap'); var test = tap.test; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "test"); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); }); sns.publish({}, function(err, data){ }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, "test"); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); st.equals(AWS.SNS.isSinonProxy, true); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, "test"); }); var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB(); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #168 from abetomo/check_test_code_with_eslint Check test code with eslint <DFF> @@ -1,7 +1,7 @@ -var tap = require('tap'); -var test = tap.test; +var tap = require('tap'); +var test = tap.test; var awsMock = require('../index.js'); -var AWS = require('aws-sdk'); +var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; @@ -24,7 +24,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ @@ -74,11 +74,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); @@ -87,11 +87,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); @@ -299,7 +299,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); st.equals(AWS.SNS.isSinonProxy, true); @@ -310,7 +310,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); @@ -324,15 +324,15 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); - var sns = new AWS.SNS(); + var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB();
14
Merge pull request #168 from abetomo/check_test_code_with_eslint
14
.js
test
apache-2.0
dwyl/aws-sdk-mock
583
<NME> index.test.js <BEF> var tap = require('tap'); var test = tap.test; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "test"); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); }); sns.publish({}, function(err, data){ }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, "test"); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); st.equals(AWS.SNS.isSinonProxy, true); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, "test"); }); var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB(); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #168 from abetomo/check_test_code_with_eslint Check test code with eslint <DFF> @@ -1,7 +1,7 @@ -var tap = require('tap'); -var test = tap.test; +var tap = require('tap'); +var test = tap.test; var awsMock = require('../index.js'); -var AWS = require('aws-sdk'); +var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); var Readable = require('stream').Readable; @@ -24,7 +24,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ @@ -74,11 +74,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); @@ -87,11 +87,11 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); @@ -299,7 +299,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); st.equals(AWS.SNS.isSinonProxy, true); @@ -310,7 +310,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); var sns = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); @@ -324,15 +324,15 @@ test('AWS.mock function should mock AWS service and method on the service', func }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, "message"); + callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ - callback(null, "test"); + callback(null, 'test'); }); - var sns = new AWS.SNS(); + var sns = new AWS.SNS(); var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB();
14
Merge pull request #168 from abetomo/check_test_code_with_eslint
14
.js
test
apache-2.0
dwyl/aws-sdk-mock
584
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "6" - "8" - "10" before_install: - pip install --user codecov after_success: <MSG> Add Node.js 12 to CI setting <DFF> @@ -4,6 +4,7 @@ node_js: - "6" - "8" - "10" + - "12" before_install: - pip install --user codecov after_success:
1
Add Node.js 12 to CI setting
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
585
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "6" - "8" - "10" before_install: - pip install --user codecov after_success: <MSG> Add Node.js 12 to CI setting <DFF> @@ -4,6 +4,7 @@ node_js: - "6" - "8" - "10" + - "12" before_install: - pip install --user codecov after_success:
1
Add Node.js 12 to CI setting
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
586
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; AWS.config.paramValidation = false; tap.afterEach(function (done) { awsMock.restore(); done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { st.equals(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); awsMock.restore('CloudSearchDomain', 'doesnotexist'); console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); console.log(e); } }); t.end(); }); const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge branch 'master' into master <DFF> @@ -10,9 +10,8 @@ const Readable = require('stream').Readable; AWS.config.paramValidation = false; -tap.afterEach(function (done) { +tap.afterEach(() => { awsMock.restore(); - done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ @@ -265,6 +264,19 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); })); }); + t.test('request object createReadStream works with returned streams', function(st) { + awsMock.mock('S3', 'getObject', () => { + const bodyStream = new Readable(); + bodyStream.push('body'); + bodyStream.push(null); + return bodyStream; + }); + const stream = new AWS.S3().getObject('getObject').createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body'); + st.end(); + })); + }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); @@ -527,9 +539,11 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(stub.stub.isSinonProxy, true); st.end(); }); + t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { + awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); @@ -537,6 +551,7 @@ test('AWS.mock function should mock AWS service and method on the service', func console.log(e); } }); + t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { @@ -547,6 +562,27 @@ test('AWS.mock function should mock AWS service and method on the service', func console.log(e); } }); + + t.test('Mocked service should allow chained calls after listening to events', function (st) { + awsMock.mock('S3', 'getObject'); + const s3 = new AWS.S3(); + const req = s3.getObject({Bucket: 'b', notKey: 'k'}); + st.equals(req.on('httpHeaders', ()=>{}), req); + st.end(); + }); + + t.test('Mocked service should return replaced function when request send is called', function(st) { + awsMock.mock('S3', 'getObject', {Body: 'body'}); + let returnedValue = ''; + const s3 = new AWS.S3(); + const req = s3.getObject('getObject', {}); + req.send(async (err, data) => { + returnedValue = data.Body; + }); + st.equals(returnedValue, 'body'); + st.end(); + }); + t.end(); });
38
Merge branch 'master' into master
2
.js
test
apache-2.0
dwyl/aws-sdk-mock
587
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; AWS.config.paramValidation = false; tap.afterEach(function (done) { awsMock.restore(); done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { st.equals(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); awsMock.restore('CloudSearchDomain', 'doesnotexist'); console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); console.log(e); } }); t.end(); }); const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge branch 'master' into master <DFF> @@ -10,9 +10,8 @@ const Readable = require('stream').Readable; AWS.config.paramValidation = false; -tap.afterEach(function (done) { +tap.afterEach(() => { awsMock.restore(); - done(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ @@ -265,6 +264,19 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); })); }); + t.test('request object createReadStream works with returned streams', function(st) { + awsMock.mock('S3', 'getObject', () => { + const bodyStream = new Readable(); + bodyStream.push('body'); + bodyStream.push(null); + return bodyStream; + }); + const stream = new AWS.S3().getObject('getObject').createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body'); + st.end(); + })); + }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); @@ -527,9 +539,11 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(stub.stub.isSinonProxy, true); st.end(); }); + t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { + awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); @@ -537,6 +551,7 @@ test('AWS.mock function should mock AWS service and method on the service', func console.log(e); } }); + t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { @@ -547,6 +562,27 @@ test('AWS.mock function should mock AWS service and method on the service', func console.log(e); } }); + + t.test('Mocked service should allow chained calls after listening to events', function (st) { + awsMock.mock('S3', 'getObject'); + const s3 = new AWS.S3(); + const req = s3.getObject({Bucket: 'b', notKey: 'k'}); + st.equals(req.on('httpHeaders', ()=>{}), req); + st.end(); + }); + + t.test('Mocked service should return replaced function when request send is called', function(st) { + awsMock.mock('S3', 'getObject', {Body: 'body'}); + let returnedValue = ''; + const s3 = new AWS.S3(); + const req = s3.getObject('getObject', {}); + req.send(async (err, data) => { + returnedValue = data.Body; + }); + st.equals(returnedValue, 'body'); + st.end(); + }); + t.end(); });
38
Merge branch 'master' into master
2
.js
test
apache-2.0
dwyl/aws-sdk-mock
588
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #62 from dr-impossible/master Added documentation for configuring promises <DFF> @@ -167,6 +167,22 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); **/ ``` +### Configuring promises + +If your environment lacks a global Promise contstructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. + +Example (if Q is your promise library of choice): +```js +var AWS = require('aws-sdk-mock'), + Q = require('q'); + +AWS.Promise = Q.Promise; + +/** + TESTS +**/ +``` + ## Documentation ### `AWS.mock(service, method, replace)`
16
Merge pull request #62 from dr-impossible/master
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
589
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #62 from dr-impossible/master Added documentation for configuring promises <DFF> @@ -167,6 +167,22 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); **/ ``` +### Configuring promises + +If your environment lacks a global Promise contstructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. + +Example (if Q is your promise library of choice): +```js +var AWS = require('aws-sdk-mock'), + Q = require('q'); + +AWS.Promise = Q.Promise; + +/** + TESTS +**/ +``` + ## Documentation ### `AWS.mock(service, method, replace)`
16
Merge pull request #62 from dr-impossible/master
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
590
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = ~services[service].methodMocks.indexOf(method); if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; } /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Removes bitwise operator <DFF> @@ -32,7 +32,7 @@ AWS.mock = function(service, method, replace) { services[service].methodMocks = [] mockService(service, method, replace); } else { - var methodMockExists = ~services[service].methodMocks.indexOf(method); + var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; }
1
Removes bitwise operator
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
591
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = ~services[service].methodMocks.indexOf(method); if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; } /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Removes bitwise operator <DFF> @@ -32,7 +32,7 @@ AWS.mock = function(service, method, replace) { services[service].methodMocks = [] mockService(service, method, replace); } else { - var methodMockExists = ~services[service].methodMocks.indexOf(method); + var methodMockExists = services[service].methodMocks.indexOf(method) > -1 ; if (!methodMockExists) { mockServiceMethod(service, method, replace); } else { return; }
1
Removes bitwise operator
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
592
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }) }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Add tests for environments with native Promises <DFF> @@ -82,6 +82,50 @@ test('AWS.mock function should mock AWS service and method on the service', func }) }); }); + if (typeof(Promise) === 'function') { + t.test('promises are supported', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(error, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise() + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }) + t.test('promises can be configured', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + function P(handler) { + var self = this + function yay (value) { + self.value = value + } + handler(yay, function(){}) + } + P.prototype.then = function(yay) { if (this.value) yay(this.value) }; + AWS.config.setPromisesDependency(P) + var promise = lambda.getFunction({}).promise() + st.equals(promise.constructor.name, 'P') + promise.then(function(data) { + st.equals(data, 'message'); + st.end(); + }); + }) + } t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
44
Add tests for environments with native Promises
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
593
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }) }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Add tests for environments with native Promises <DFF> @@ -82,6 +82,50 @@ test('AWS.mock function should mock AWS service and method on the service', func }) }); }); + if (typeof(Promise) === 'function') { + t.test('promises are supported', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(error, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise() + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }) + t.test('promises can be configured', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + function P(handler) { + var self = this + function yay (value) { + self.value = value + } + handler(yay, function(){}) + } + P.prototype.then = function(yay) { if (this.value) yay(this.value) }; + AWS.config.setPromisesDependency(P) + var promise = lambda.getFunction({}).promise() + st.equals(promise.constructor.name, 'P') + promise.then(function(data) { + st.equals(data, 'message'); + st.end(); + }); + }) + } t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
44
Add tests for environments with native Promises
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
594
<NME> .travis.yml <BEF> language: node_js node_js: - "4.2.3" - "node" before_install: - pip install --user codecov after_success: <MSG> Add testing on more node versions <DFF> @@ -1,7 +1,9 @@ language: node_js node_js: - - "4.2.3" - - "node" + - "4" + - "6" + - "8" + - "10" before_install: - pip install --user codecov after_success:
4
Add testing on more node versions
2
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
595
<NME> .travis.yml <BEF> language: node_js node_js: - "4.2.3" - "node" before_install: - pip install --user codecov after_success: <MSG> Add testing on more node versions <DFF> @@ -1,7 +1,9 @@ language: node_js node_js: - - "4.2.3" - - "node" + - "4" + - "6" + - "8" + - "10" before_install: - pip install --user codecov after_success:
4
Add testing on more node versions
2
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
596
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { st.equals(typeof req.on, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Add `send` method to request object Reference: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html <DFF> @@ -259,6 +259,13 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(typeof req.on, 'function'); st.end(); }); + t.test('call send method of request object', function(st) { + awsMock.mock('S3', 'getObject', {Body: 'body'}); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + st.equals(typeof req.send, 'function'); + st.end(); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
7
Add `send` method to request object
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
597
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { st.equals(typeof req.on, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Add `send` method to request object Reference: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html <DFF> @@ -259,6 +259,13 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(typeof req.on, 'function'); st.end(); }); + t.test('call send method of request object', function(st) { + awsMock.mock('S3', 'getObject', {Body: 'body'}); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}); + st.equals(typeof req.send, 'function'); + st.end(); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
7
Add `send` method to request object
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
598
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { Checks if a mock of a method on a service already exists before creating it */ AWS.mock = function(service, method, replace) { if (!services[service]) { services[service] = {}; services[service].Constructor = _AWS[service]; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } Saves the stub to the services object so it can be restored after the test */ function mockService(service, method, replace) { var client = new services[service].Constructor(); client.sandbox = sinon.sandbox.create(); services[service].client = client; mockServiceMethod(service, method, replace); mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> added config parameter for requires AWS configurations <DFF> @@ -25,12 +25,12 @@ var services = {}; Checks if a mock of a method on a service already exists before creating it */ -AWS.mock = function(service, method, replace) { +AWS.mock = function(service, method, replace, config) { if (!services[service]) { services[service] = {}; services[service].Constructor = _AWS[service]; services[service].methodMocks = [] - mockService(service, method, replace); + mockService(service, method, replace, config); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { @@ -49,8 +49,8 @@ AWS.mock = function(service, method, replace) { Saves the stub to the services object so it can be restored after the test */ -function mockService(service, method, replace) { - var client = new services[service].Constructor(); +function mockService(service, method, replace, config) { + var client = new services[service].Constructor(config); client.sandbox = sinon.sandbox.create(); services[service].client = client; mockServiceMethod(service, method, replace);
4
added config parameter for requires AWS configurations
4
.js
js
apache-2.0
dwyl/aws-sdk-mock
599
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { Checks if a mock of a method on a service already exists before creating it */ AWS.mock = function(service, method, replace) { if (!services[service]) { services[service] = {}; services[service].Constructor = _AWS[service]; services[service].methodMocks = [] mockService(service, method, replace); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } Saves the stub to the services object so it can be restored after the test */ function mockService(service, method, replace) { var client = new services[service].Constructor(); client.sandbox = sinon.sandbox.create(); services[service].client = client; mockServiceMethod(service, method, replace); mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> added config parameter for requires AWS configurations <DFF> @@ -25,12 +25,12 @@ var services = {}; Checks if a mock of a method on a service already exists before creating it */ -AWS.mock = function(service, method, replace) { +AWS.mock = function(service, method, replace, config) { if (!services[service]) { services[service] = {}; services[service].Constructor = _AWS[service]; services[service].methodMocks = [] - mockService(service, method, replace); + mockService(service, method, replace, config); } else { var methodMockExists = services[service].methodMocks.indexOf(method) > -1; if (!methodMockExists) { @@ -49,8 +49,8 @@ AWS.mock = function(service, method, replace) { Saves the stub to the services object so it can be restored after the test */ -function mockService(service, method, replace) { - var client = new services[service].Constructor(); +function mockService(service, method, replace, config) { + var client = new services[service].Constructor(config); client.sandbox = sinon.sandbox.create(); services[service].client = client; mockServiceMethod(service, method, replace);
4
added config parameter for requires AWS configurations
4
.js
js
apache-2.0
dwyl/aws-sdk-mock