Search is not available for this dataset
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
|
---|---|---|---|---|---|---|---|---|
700 | <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> Merge pull request #114 from shaunc/spy-can-return-promise
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 | Merge pull request #114 from shaunc/spy-can-return-promise | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
701 | <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> Merge pull request #114 from shaunc/spy-can-return-promise
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 | Merge pull request #114 from shaunc/spy-can-return-promise | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
702 | <NME> index.test.js
<BEF> var test = require('tape');
var awsMock = require('../index.js');
var AWS = require('aws-sdk');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
AWS.config.paramValidation = false;
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();
});
});
st.end();
});
});
t.test('mock function replaces method with replace function', function(st){
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
});
});
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) {
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equals(data.test, 'message');
awsMock.restore('S3');
st.end();
});
});
st.end();
});
});
});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
awsMock.restore('S3', 'getObject');
st.end();
});
});
st.end();
});
var s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
awsMock.restore('S3');
st.end();
});
});
st.end();
});
});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
awsMock.restore('S3', 'getObject');
st.end();
});
});
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');
});
});
sns.publish({}, function(err, data){
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
});
});
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');
});
});
sns.subscribe({}, function(err, data){
st.equals(data, 'test');
awsMock.restore('SNS');
st.end();
});
});
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();
});
});
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');
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('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) {
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.end();
});
t.test('promises work with async completion', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.restore('Lambda', 'createFunction');
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
});
});
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) {
});
});
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
});
});
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){
req = s3.getObject('getObject');
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
awsMock.restore('S3', 'getObject');
st.end();
}));
});
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
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 stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
awsMock.restore('S3', 'getObject');
st.end();
}));
});
const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
});
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){
docClient.query({}, function(err, data){
console.warn(err);
st.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
});
});
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');
});
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();
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
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');
} catch (e) {
console.log(e);
}
});
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
st.end();
});
});
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
});
});
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.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
awsMock.restore();
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);
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message2');
awsMock.restore('SNS');
st.end();
});
});
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
awsMock.restore();
st.end();
});
t.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 #144 from jstewmon/createReadStream-stream
support passing a Readable stream as the stub for S3.GetObject
<DFF> @@ -1,18 +1,24 @@
-var test = require('tape');
+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;
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){
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();
});
});
@@ -23,7 +29,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
- awsMock.restore('SNS');
st.end();
});
});
@@ -37,7 +42,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equals(data.test, 'message');
- awsMock.restore('S3');
st.end();
});
});
@@ -48,7 +52,6 @@ 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();
});
});
@@ -57,7 +60,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
- awsMock.restore('S3');
st.end();
});
});
@@ -67,7 +69,6 @@ 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();
});
});
@@ -81,7 +82,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
sns.publish({}, function(err, data){
st.equals(data, 'message');
- awsMock.restore('SNS');
st.end();
});
});
@@ -95,7 +95,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
sns.subscribe({}, function(err, data){
st.equals(data, 'test');
- awsMock.restore('SNS');
st.end();
});
});
@@ -117,8 +116,6 @@ 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');
@@ -137,8 +134,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
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')
@@ -169,8 +164,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
});
t.test('promises work with async completion', function(st){
- awsMock.restore('Lambda', 'getFunction');
- awsMock.restore('Lambda', 'createFunction');
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
@@ -189,7 +182,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
t.test('promises can be configured', function(st){
- awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
@@ -224,7 +216,17 @@ 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 streams', function(st) {
+ var bodyStream = new Readable();
+ bodyStream.push('body');
+ bodyStream.push(null);
+ awsMock.mock('S3', 'getObject', bodyStream);
+ var stream = new AWS.S3().getObject('getObject').createReadStream();
+ stream.pipe(concatStream(function(actual) {
+ st.equals(actual.toString(), 'body');
st.end();
}));
});
@@ -235,7 +237,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -246,7 +247,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -257,7 +257,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -268,7 +267,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -383,7 +381,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
docClient.query({}, function(err, data){
console.warn(err);
st.equals(data, 'test');
- awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
});
});
@@ -451,12 +448,12 @@ 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) {
+ t.skip('Mocked service should return the sinon stub', function(st) {
+ // TODO: the stub is only returned if an instance was already constructed
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
st.end();
});
- t.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 {
@@ -466,8 +463,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
} catch (e) {
console.log(e);
}
-
});
+ t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
@@ -477,7 +474,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
- awsMock.restore('SNS');
st.end();
});
});
@@ -488,8 +484,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
- awsMock.restore();
-
st.end();
});
t.end();
@@ -503,7 +497,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message2');
- awsMock.restore('SNS');
st.end();
});
});
@@ -515,7 +508,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
- awsMock.restore();
st.end();
});
t.end();
| 22 | Merge pull request #144 from jstewmon/createReadStream-stream | 30 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
703 | <NME> index.test.js
<BEF> var test = require('tape');
var awsMock = require('../index.js');
var AWS = require('aws-sdk');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
AWS.config.paramValidation = false;
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();
});
});
st.end();
});
});
t.test('mock function replaces method with replace function', function(st){
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
});
});
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) {
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equals(data.test, 'message');
awsMock.restore('S3');
st.end();
});
});
st.end();
});
});
});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
awsMock.restore('S3', 'getObject');
st.end();
});
});
st.end();
});
var s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
awsMock.restore('S3');
st.end();
});
});
st.end();
});
});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
awsMock.restore('S3', 'getObject');
st.end();
});
});
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');
});
});
sns.publish({}, function(err, data){
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
});
});
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');
});
});
sns.subscribe({}, function(err, data){
st.equals(data, 'test');
awsMock.restore('SNS');
st.end();
});
});
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();
});
});
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');
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('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) {
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.end();
});
t.test('promises work with async completion', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.restore('Lambda', 'createFunction');
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
});
});
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) {
});
});
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
});
});
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){
req = s3.getObject('getObject');
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
awsMock.restore('S3', 'getObject');
st.end();
}));
});
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
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 stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
awsMock.restore('S3', 'getObject');
st.end();
}));
});
const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
});
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){
docClient.query({}, function(err, data){
console.warn(err);
st.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
});
});
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');
});
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();
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
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');
} catch (e) {
console.log(e);
}
});
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
st.end();
});
});
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
});
});
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.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
awsMock.restore();
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);
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message2');
awsMock.restore('SNS');
st.end();
});
});
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
awsMock.restore();
st.end();
});
t.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 #144 from jstewmon/createReadStream-stream
support passing a Readable stream as the stub for S3.GetObject
<DFF> @@ -1,18 +1,24 @@
-var test = require('tape');
+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;
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){
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();
});
});
@@ -23,7 +29,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
- awsMock.restore('SNS');
st.end();
});
});
@@ -37,7 +42,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equals(data.test, 'message');
- awsMock.restore('S3');
st.end();
});
});
@@ -48,7 +52,6 @@ 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();
});
});
@@ -57,7 +60,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
- awsMock.restore('S3');
st.end();
});
});
@@ -67,7 +69,6 @@ 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();
});
});
@@ -81,7 +82,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
sns.publish({}, function(err, data){
st.equals(data, 'message');
- awsMock.restore('SNS');
st.end();
});
});
@@ -95,7 +95,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
sns.subscribe({}, function(err, data){
st.equals(data, 'test');
- awsMock.restore('SNS');
st.end();
});
});
@@ -117,8 +116,6 @@ 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');
@@ -137,8 +134,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
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')
@@ -169,8 +164,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
});
t.test('promises work with async completion', function(st){
- awsMock.restore('Lambda', 'getFunction');
- awsMock.restore('Lambda', 'createFunction');
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
@@ -189,7 +182,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
t.test('promises can be configured', function(st){
- awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
@@ -224,7 +216,17 @@ 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 streams', function(st) {
+ var bodyStream = new Readable();
+ bodyStream.push('body');
+ bodyStream.push(null);
+ awsMock.mock('S3', 'getObject', bodyStream);
+ var stream = new AWS.S3().getObject('getObject').createReadStream();
+ stream.pipe(concatStream(function(actual) {
+ st.equals(actual.toString(), 'body');
st.end();
}));
});
@@ -235,7 +237,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -246,7 +247,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -257,7 +257,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -268,7 +267,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
- awsMock.restore('S3', 'getObject');
st.end();
}));
});
@@ -383,7 +381,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
docClient.query({}, function(err, data){
console.warn(err);
st.equals(data, 'test');
- awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
});
});
@@ -451,12 +448,12 @@ 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) {
+ t.skip('Mocked service should return the sinon stub', function(st) {
+ // TODO: the stub is only returned if an instance was already constructed
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
st.end();
});
- t.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 {
@@ -466,8 +463,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
} catch (e) {
console.log(e);
}
-
});
+ t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
@@ -477,7 +474,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
- awsMock.restore('SNS');
st.end();
});
});
@@ -488,8 +484,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
- awsMock.restore();
-
st.end();
});
t.end();
@@ -503,7 +497,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message2');
- awsMock.restore('SNS');
st.end();
});
});
@@ -515,7 +508,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
- awsMock.restore();
st.end();
});
t.end();
| 22 | Merge pull request #144 from jstewmon/createReadStream-stream | 30 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
704 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
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');
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) {
});
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "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> Merge pull request #41 from motiz88/param-validation
Feature proposal: Validate service method params if config.paramValidation is set
<DFF> @@ -4,6 +4,8 @@ var AWS = require('aws-sdk');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
+AWS.config.paramValidation = false;
+
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');
@@ -40,6 +42,24 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
});
+ t.test('method fails on invalid input if paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var 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 succeeds on valid input when paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var s3 = new AWS.S3({paramValidation: true});
+ s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
+ st.notOk(err);
+ st.equals(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");
| 20 | Merge pull request #41 from motiz88/param-validation | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
705 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
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');
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) {
});
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "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> Merge pull request #41 from motiz88/param-validation
Feature proposal: Validate service method params if config.paramValidation is set
<DFF> @@ -4,6 +4,8 @@ var AWS = require('aws-sdk');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
+AWS.config.paramValidation = false;
+
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');
@@ -40,6 +42,24 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
});
+ t.test('method fails on invalid input if paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var 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 succeeds on valid input when paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var s3 = new AWS.S3({paramValidation: true});
+ s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
+ st.notOk(err);
+ st.equals(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");
| 20 | Merge pull request #41 from motiz88/param-validation | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
706 | <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
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');
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');
});
st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
var dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.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');
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
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 replace-istanbul-by-nyc
<DFF> @@ -252,11 +252,24 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('call on 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.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");
});
- var sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
@@ -372,7 +385,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
- var dynamoDb = new AWS.DynamoDB();
+ dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
@@ -427,7 +440,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
- var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
| 15 | Merge branch 'master' into replace-istanbul-by-nyc | 3 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
707 | <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
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');
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');
});
st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
var dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.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');
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
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 replace-istanbul-by-nyc
<DFF> @@ -252,11 +252,24 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('call on 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.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");
});
- var sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
@@ -372,7 +385,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
- var dynamoDb = new AWS.DynamoDB();
+ dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
@@ -427,7 +440,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
- var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
| 15 | Merge branch 'master' into replace-istanbul-by-nyc | 3 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
708 | <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
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> Merge branch 'master' into patch-1
<DFF> @@ -252,6 +252,20 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('call on 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.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");
| 14 | Merge branch 'master' into patch-1 | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
709 | <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
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> Merge branch 'master' into patch-1
<DFF> @@ -252,6 +252,20 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('call on 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.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");
| 14 | Merge branch 'master' into patch-1 | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
710 | <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> Merge pull request #182 from daniel-hayes/master
Fix readme typo
<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 | Merge pull request #182 from daniel-hayes/master | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
711 | <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> Merge pull request #182 from daniel-hayes/master
Fix readme typo
<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 | Merge pull request #182 from daniel-hayes/master | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
712 | <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.restore('SNS');
// st.end();
// })
// t.test('only the method on the service is restored', function(st){
// awsMock.restore('SNS', 'publish');
// st.end();
// })
// t.test('all the services are restored', function(st){
// awsMock.restore('SNS', 'publish');
// st.end();
// })
t.end();
});
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> Adds if/else to AWS.restore
Options for restoring an entire service, only one method or restoring all the methods and services depending on the number of arguments supplied. Also adds tests for and instructions to the readme
<DFF> @@ -51,17 +51,54 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
})
})
- // t.test('all the methods on a service are restored', function(st){
- // awsMock.restore('SNS');
- // st.end();
- // })
- // t.test('only the method on the service is restored', function(st){
- // awsMock.restore('SNS', 'publish');
- // st.end();
- // })
- // t.test('all the services are restored', function(st){
- // awsMock.restore('SNS', 'publish');
- // 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();
});
| 49 | Adds if/else to AWS.restore | 12 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
713 | <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.restore('SNS');
// st.end();
// })
// t.test('only the method on the service is restored', function(st){
// awsMock.restore('SNS', 'publish');
// st.end();
// })
// t.test('all the services are restored', function(st){
// awsMock.restore('SNS', 'publish');
// st.end();
// })
t.end();
});
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> Adds if/else to AWS.restore
Options for restoring an entire service, only one method or restoring all the methods and services depending on the number of arguments supplied. Also adds tests for and instructions to the readme
<DFF> @@ -51,17 +51,54 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
})
})
- // t.test('all the methods on a service are restored', function(st){
- // awsMock.restore('SNS');
- // st.end();
- // })
- // t.test('only the method on the service is restored', function(st){
- // awsMock.restore('SNS', 'publish');
- // st.end();
- // })
- // t.test('all the services are restored', function(st){
- // awsMock.restore('SNS', 'publish');
- // 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();
});
| 49 | Adds if/else to AWS.restore | 12 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
714 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- 0.10.36
- "4.2.3"
before_install:
- pip install --user codecov
after_success:
<MSG> Remove node 0.10 from travis
<DFF> @@ -1,7 +1,7 @@
language: node_js
node_js:
- - 0.10.36
- "4.2.3"
+ - "node"
before_install:
- pip install --user codecov
after_success:
| 1 | Remove node 0.10 from travis | 1 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
715 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- 0.10.36
- "4.2.3"
before_install:
- pip install --user codecov
after_success:
<MSG> Remove node 0.10 from travis
<DFF> @@ -1,7 +1,7 @@
language: node_js
node_js:
- - 0.10.36
- "4.2.3"
+ - "node"
before_install:
- pip install --user codecov
after_success:
| 1 | Remove node 0.10 from travis | 1 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
716 | <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> Merge pull request #239 from abetomo/upgrade_devDependencies
chore(deps): upgrade devDependencies
<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 | Merge pull request #239 from abetomo/upgrade_devDependencies | 2 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
717 | <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> Merge pull request #239 from abetomo/upgrade_devDependencies
chore(deps): upgrade devDependencies
<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 | Merge pull request #239 from abetomo/upgrade_devDependencies | 2 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
718 | <NME> CONTRIBUTING.md
<BEF> ADDFILE
<MSG> Merge pull request #80 from dwyl/contributing
Create CONTRIBUTING.md
<DFF> @@ -0,0 +1,1 @@
+_**Please read** our_ [**contribution guide**](https://github.com/dwyl/contributing) (_thank you_!)
| 1 | Merge pull request #80 from dwyl/contributing | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
719 | <NME> CONTRIBUTING.md
<BEF> ADDFILE
<MSG> Merge pull request #80 from dwyl/contributing
Create CONTRIBUTING.md
<DFF> @@ -0,0 +1,1 @@
+_**Please read** our_ [**contribution guide**](https://github.com/dwyl/contributing) (_thank you_!)
| 1 | Merge pull request #80 from dwyl/contributing | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
720 | <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
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(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> Merge pull request #94 from abetomo/add_on_method
Add `on` method to request object
<DFF> @@ -252,6 +252,13 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('call on 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.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");
| 7 | Merge pull request #94 from abetomo/add_on_method | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
721 | <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
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(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> Merge pull request #94 from abetomo/add_on_method
Add `on` method to request object
<DFF> @@ -252,6 +252,13 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('call on 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.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");
| 7 | Merge pull request #94 from abetomo/add_on_method | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
722 | <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();
console.log(e);
}
});
t.end();
});
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 #245 from GabrielLomba/master
Fix 'on' chained calls usage with mocked methods
<DFF> @@ -493,6 +493,14 @@ 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.end();
});
| 8 | Merge pull request #245 from GabrielLomba/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
723 | <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();
console.log(e);
}
});
t.end();
});
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 #245 from GabrielLomba/master
Fix 'on' chained calls usage with mocked methods
<DFF> @@ -493,6 +493,14 @@ 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.end();
});
| 8 | Merge pull request #245 from GabrielLomba/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
724 | <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) => {
}
```
### 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:
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
Example:
```js
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
```
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 #149 from jeznag/patch-1
More examples to help with Typescript support
<DFF> @@ -112,6 +112,30 @@ exports.handler = function(event, context) {
}
```
+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(() => {
+ var sns = AWS.SNS();
+ var dynamoDb = AWS.DynamoDB();
+ // do something with the services e.g. sns.publish
+ });
+}
+```
+
+Example 2 (will work):
+```js
+exports.handler = function(event, context) {
+ var sns = AWS.SNS();
+ var 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:
@@ -178,10 +202,14 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec
Example:
```js
-var AWS = require('aws-sdk-mock');
-var AWS_SDK = require('aws-sdk')
-
-AWS.setSDKInstance(AWS_SDK);
+// test code
+const AWSMock = require('aws-sdk-mock');
+import AWS = require('aws-sdk');
+AWSMock.setSDKInstance(AWS);
+AWSMock.mock('SQS', /* ... */);
+
+// implementation code
+const sqs = new AWS.SQS();
```
| 32 | Merge pull request #149 from jeznag/patch-1 | 4 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
725 | <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) => {
}
```
### 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:
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
Example:
```js
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
```
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 #149 from jeznag/patch-1
More examples to help with Typescript support
<DFF> @@ -112,6 +112,30 @@ exports.handler = function(event, context) {
}
```
+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(() => {
+ var sns = AWS.SNS();
+ var dynamoDb = AWS.DynamoDB();
+ // do something with the services e.g. sns.publish
+ });
+}
+```
+
+Example 2 (will work):
+```js
+exports.handler = function(event, context) {
+ var sns = AWS.SNS();
+ var 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:
@@ -178,10 +202,14 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec
Example:
```js
-var AWS = require('aws-sdk-mock');
-var AWS_SDK = require('aws-sdk')
-
-AWS.setSDKInstance(AWS_SDK);
+// test code
+const AWSMock = require('aws-sdk-mock');
+import AWS = require('aws-sdk');
+AWSMock.setSDKInstance(AWS);
+AWSMock.mock('SQS', /* ... */);
+
+// implementation code
+const sqs = new AWS.SQS();
```
| 32 | Merge pull request #149 from jeznag/patch-1 | 4 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
726 | <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) {
mockServiceMethod(service, services[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;
}
} else {
var stream = new Readable();
stream._read = function(size) {
if(typeof(replace) === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
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_;
}
// If the value of 'replace' is a function we call it with the arguments.
if(typeof(replace) === 'function') {
var result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
typeof result.then === 'function') {
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) {
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
if(!service) {
restoreAllServices();
} else {
if (method) {
// 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') {
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if( services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
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);
}
};
};
}
(function(){
var setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
}
}
/**
* 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> Format the code according to eslint
<DFF> @@ -48,11 +48,11 @@ AWS.mock = function(service, method, replace) {
}
// Register the method to be mocked out.
- if(!services[service].methodMocks[method]) {
+ 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) {
+ if (services[service].invoked) {
mockServiceMethod(service, services[service].client, method, replace);
}
}
@@ -169,7 +169,7 @@ function mockServiceMethod(service, client, method, replace) {
} else {
var stream = new Readable();
stream._read = function(size) {
- if(typeof(replace) === 'string' || Buffer.isBuffer(replace)) {
+ if (typeof(replace) === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
@@ -201,7 +201,7 @@ function mockServiceMethod(service, client, method, replace) {
}
// If the value of 'replace' is a function we call it with the arguments.
- if(typeof(replace) === 'function') {
+ if (typeof(replace) === 'function') {
var result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
typeof result.then === 'function') {
@@ -224,7 +224,7 @@ function mockServiceMethod(service, client, method, replace) {
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
- if(!service) {
+ if (!service) {
restoreAllServices();
} else {
if (method) {
@@ -250,7 +250,7 @@ function restoreAllServices() {
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
- if( services[service].stub)
+ if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
@@ -282,7 +282,7 @@ function restoreMethod(service, method) {
}
-(function(){
+(function() {
var setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
| 7 | Format the code according to eslint | 7 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
727 | <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) {
mockServiceMethod(service, services[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;
}
} else {
var stream = new Readable();
stream._read = function(size) {
if(typeof(replace) === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
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_;
}
// If the value of 'replace' is a function we call it with the arguments.
if(typeof(replace) === 'function') {
var result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
typeof result.then === 'function') {
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) {
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
if(!service) {
restoreAllServices();
} else {
if (method) {
// 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') {
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if( services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
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);
}
};
};
}
(function(){
var setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
}
}
/**
* 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> Format the code according to eslint
<DFF> @@ -48,11 +48,11 @@ AWS.mock = function(service, method, replace) {
}
// Register the method to be mocked out.
- if(!services[service].methodMocks[method]) {
+ 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) {
+ if (services[service].invoked) {
mockServiceMethod(service, services[service].client, method, replace);
}
}
@@ -169,7 +169,7 @@ function mockServiceMethod(service, client, method, replace) {
} else {
var stream = new Readable();
stream._read = function(size) {
- if(typeof(replace) === 'string' || Buffer.isBuffer(replace)) {
+ if (typeof(replace) === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
@@ -201,7 +201,7 @@ function mockServiceMethod(service, client, method, replace) {
}
// If the value of 'replace' is a function we call it with the arguments.
- if(typeof(replace) === 'function') {
+ if (typeof(replace) === 'function') {
var result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
typeof result.then === 'function') {
@@ -224,7 +224,7 @@ function mockServiceMethod(service, client, method, replace) {
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
- if(!service) {
+ if (!service) {
restoreAllServices();
} else {
if (method) {
@@ -250,7 +250,7 @@ function restoreAllServices() {
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
- if( services[service].stub)
+ if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
@@ -282,7 +282,7 @@ function restoreMethod(service, method) {
}
-(function(){
+(function() {
var setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
| 7 | Format the code according to eslint | 7 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
728 | <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> Merge pull request #137 from abetomo/add_send_method
Add `send` method to request object
<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 | Merge pull request #137 from abetomo/add_send_method | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
729 | <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> Merge pull request #137 from abetomo/add_send_method
Add `send` method to request object
<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 | Merge pull request #137 from abetomo/add_send_method | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
730 | <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');
});
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.ok(signer);
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
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 #183 from psaxton/issues/169
Update tests as requested in PR #170
<DFF> @@ -492,11 +492,11 @@ 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');
- st.ok(signer);
- st.end();
+ 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();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
| 5 | Merge pull request #183 from psaxton/issues/169 | 5 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
731 | <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');
});
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.ok(signer);
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
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 #183 from psaxton/issues/169
Update tests as requested in PR #170
<DFF> @@ -492,11 +492,11 @@ 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');
- st.ok(signer);
- st.end();
+ 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();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
| 5 | Merge pull request #183 from psaxton/issues/169 | 5 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
732 | <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 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.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 a Jest/Sinon replace function to define only the callback function
<DFF> @@ -688,6 +688,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 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();
});
| 11 | Allow a Jest/Sinon replace function to define only the callback function | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
733 | <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 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.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 a Jest/Sinon replace function to define only the callback function
<DFF> @@ -688,6 +688,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 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();
});
| 11 | Allow a Jest/Sinon replace function to define only the callback function | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
734 | <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", new Buffer(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'});
});
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> Corrected spelling of 'Bffer' to 'Buffer'
A minor change, but it distracted me when encountered
<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", new Buffer(require("fs").readFileSync("testFile.csv")));
/**
| 1 | Corrected spelling of 'Bffer' to 'Buffer' A minor change, but it distracted me when encountered | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
735 | <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", new Buffer(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'});
});
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> Corrected spelling of 'Bffer' to 'Buffer'
A minor change, but it distracted me when encountered
<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", new Buffer(require("fs").readFileSync("testFile.csv")));
/**
| 1 | Corrected spelling of 'Bffer' to 'Buffer' A minor change, but it distracted me when encountered | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
736 | <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();
});
console.log(e);
}
});
t.end();
});
}
});
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 method is restored, it should be restored on all clients
<DFF> @@ -113,6 +113,27 @@ 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');
@@ -517,6 +538,16 @@ 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 {
+ awsMock.restore('CloudFormation');
+ awsMock.restore('UnknownService');
+ st.end();
+ } catch (e) {
+ console.log(e);
+ }
+ });
t.end();
});
| 31 | When method is restored, it should be restored on all clients | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
737 | <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();
});
console.log(e);
}
});
t.end();
});
}
});
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 method is restored, it should be restored on all clients
<DFF> @@ -113,6 +113,27 @@ 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');
@@ -517,6 +538,16 @@ 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 {
+ awsMock.restore('CloudFormation');
+ awsMock.restore('UnknownService');
+ st.end();
+ } catch (e) {
+ console.log(e);
+ }
+ });
t.end();
});
| 31 | When method is restored, it should be restored on all clients | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
738 | <NME> .eslintrc.json
<BEF> {
"env": {
"browser": true,
"node": true
},
"globals": {
"Buffer": true,
"escape": true
},
"rules": {
"quotes": [2, "single"],
"strict": 0,
"curly": 0,
"no-empty": 0,
"no-multi-spaces": 2,
"no-underscore-dangle": 0,
"new-cap": 0,
"dot-notation": 0,
"no-use-before-define": 0,
"keyword-spacing": [2, {"after": true, "before": true}],
"no-trailing-spaces": 2,
"space-unary-ops": [1, { "words": true, "nonwords": false }]
}
}
<MSG> Merge pull request #184 from abetomo/fix_lint_error
Add parserOptions to .eslintrc.json
<DFF> @@ -1,24 +1,27 @@
{
"env": {
"browser": true,
- "node": true
+ "node": true
},
- "globals": {
- "Buffer": true,
- "escape": true
- },
- "rules": {
- "quotes": [2, "single"],
- "strict": 0,
- "curly": 0,
- "no-empty": 0,
- "no-multi-spaces": 2,
- "no-underscore-dangle": 0,
- "new-cap": 0,
- "dot-notation": 0,
- "no-use-before-define": 0,
- "keyword-spacing": [2, {"after": true, "before": true}],
- "no-trailing-spaces": 2,
- "space-unary-ops": [1, { "words": true, "nonwords": false }]
- }
+ "globals": {
+ "Buffer": true,
+ "escape": true
+ },
+ "parserOptions": {
+ "ecmaVersion": 2017
+ },
+ "rules": {
+ "quotes": [2, "single"],
+ "strict": 0,
+ "curly": 0,
+ "no-empty": 0,
+ "no-multi-spaces": 2,
+ "no-underscore-dangle": 0,
+ "new-cap": 0,
+ "dot-notation": 0,
+ "no-use-before-define": 0,
+ "keyword-spacing": [2, {"after": true, "before": true}],
+ "no-trailing-spaces": 2,
+ "space-unary-ops": [1, { "words": true, "nonwords": false }]
+ }
}
| 22 | Merge pull request #184 from abetomo/fix_lint_error | 19 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
739 | <NME> .eslintrc.json
<BEF> {
"env": {
"browser": true,
"node": true
},
"globals": {
"Buffer": true,
"escape": true
},
"rules": {
"quotes": [2, "single"],
"strict": 0,
"curly": 0,
"no-empty": 0,
"no-multi-spaces": 2,
"no-underscore-dangle": 0,
"new-cap": 0,
"dot-notation": 0,
"no-use-before-define": 0,
"keyword-spacing": [2, {"after": true, "before": true}],
"no-trailing-spaces": 2,
"space-unary-ops": [1, { "words": true, "nonwords": false }]
}
}
<MSG> Merge pull request #184 from abetomo/fix_lint_error
Add parserOptions to .eslintrc.json
<DFF> @@ -1,24 +1,27 @@
{
"env": {
"browser": true,
- "node": true
+ "node": true
},
- "globals": {
- "Buffer": true,
- "escape": true
- },
- "rules": {
- "quotes": [2, "single"],
- "strict": 0,
- "curly": 0,
- "no-empty": 0,
- "no-multi-spaces": 2,
- "no-underscore-dangle": 0,
- "new-cap": 0,
- "dot-notation": 0,
- "no-use-before-define": 0,
- "keyword-spacing": [2, {"after": true, "before": true}],
- "no-trailing-spaces": 2,
- "space-unary-ops": [1, { "words": true, "nonwords": false }]
- }
+ "globals": {
+ "Buffer": true,
+ "escape": true
+ },
+ "parserOptions": {
+ "ecmaVersion": 2017
+ },
+ "rules": {
+ "quotes": [2, "single"],
+ "strict": 0,
+ "curly": 0,
+ "no-empty": 0,
+ "no-multi-spaces": 2,
+ "no-underscore-dangle": 0,
+ "new-cap": 0,
+ "dot-notation": 0,
+ "no-use-before-define": 0,
+ "keyword-spacing": [2, {"after": true, "before": true}],
+ "no-trailing-spaces": 2,
+ "space-unary-ops": [1, { "words": true, "nonwords": false }]
+ }
}
| 22 | Merge pull request #184 from abetomo/fix_lint_error | 19 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
740 | <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) => {
}
```
### 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:
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
Example:
```js
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
```
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> More examples to help with Typescript support
<DFF> @@ -112,6 +112,30 @@ exports.handler = function(event, context) {
}
```
+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(() => {
+ var sns = AWS.SNS();
+ var dynamoDb = AWS.DynamoDB();
+ // do something with the services e.g. sns.publish
+ });
+}
+```
+
+Example 2 (will work):
+```js
+exports.handler = function(event, context) {
+ var sns = AWS.SNS();
+ var 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:
@@ -178,10 +202,14 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec
Example:
```js
-var AWS = require('aws-sdk-mock');
-var AWS_SDK = require('aws-sdk')
-
-AWS.setSDKInstance(AWS_SDK);
+// test code
+const AWSMock = require('aws-sdk-mock');
+import AWS = require('aws-sdk');
+AWSMock.setSDKInstance(AWS);
+AWSMock.mock('SQS', /* ... */);
+
+// implementation code
+const sqs = new AWS.SQS();
```
| 32 | More examples to help with Typescript support | 4 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
741 | <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) => {
}
```
### 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:
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
Example:
```js
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
```
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> More examples to help with Typescript support
<DFF> @@ -112,6 +112,30 @@ exports.handler = function(event, context) {
}
```
+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(() => {
+ var sns = AWS.SNS();
+ var dynamoDb = AWS.DynamoDB();
+ // do something with the services e.g. sns.publish
+ });
+}
+```
+
+Example 2 (will work):
+```js
+exports.handler = function(event, context) {
+ var sns = AWS.SNS();
+ var 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:
@@ -178,10 +202,14 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec
Example:
```js
-var AWS = require('aws-sdk-mock');
-var AWS_SDK = require('aws-sdk')
-
-AWS.setSDKInstance(AWS_SDK);
+// test code
+const AWSMock = require('aws-sdk-mock');
+import AWS = require('aws-sdk');
+AWSMock.setSDKInstance(AWS);
+AWSMock.mock('SQS', /* ... */);
+
+// implementation code
+const sqs = new AWS.SQS();
```
| 32 | More examples to help with Typescript support | 4 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
742 | <NME> simple-mock-test.js
<BEF> ADDFILE
<MSG> Sets up package.json and index.js file
<DFF> @@ -0,0 +1,28 @@
+var simple = require('simple-mock');
+var _AWS = require('aws-sdk');
+
+var core = {};
+
+exports.mock = function (service, method) {
+ core[service] = {};
+ core[service].Constructor = _AWS[service];
+ createStub(service, method, function (err, data) {
+ if (err) return console.log(err);
+ return data;
+ });
+};
+
+exports.restore = function () {
+ simple.restore();
+};
+
+function createStub (service, method, next) {
+ simple.mock(_AWS, service, function () {
+ var client = new core[service].Constructor();
+ next(null, applyMock(client, method));
+ });
+}
+
+function applyMock (client, method) {
+ return simple.mock(client, method);
+}
| 28 | Sets up package.json and index.js file | 0 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
743 | <NME> simple-mock-test.js
<BEF> ADDFILE
<MSG> Sets up package.json and index.js file
<DFF> @@ -0,0 +1,28 @@
+var simple = require('simple-mock');
+var _AWS = require('aws-sdk');
+
+var core = {};
+
+exports.mock = function (service, method) {
+ core[service] = {};
+ core[service].Constructor = _AWS[service];
+ createStub(service, method, function (err, data) {
+ if (err) return console.log(err);
+ return data;
+ });
+};
+
+exports.restore = function () {
+ simple.restore();
+};
+
+function createStub (service, method, next) {
+ simple.mock(_AWS, service, function () {
+ var client = new core[service].Constructor();
+ next(null, applyMock(client, method));
+ });
+}
+
+function applyMock (client, method) {
+ return simple.mock(client, method);
+}
| 28 | Sets up package.json and index.js file | 0 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
744 | <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.equals(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.end();
});
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 #246 from michaelpinnell/master
Fix request.send not resolving
<DFF> @@ -501,6 +501,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
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();
});
| 13 | Merge pull request #246 from michaelpinnell/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
745 | <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.equals(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.end();
});
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 #246 from michaelpinnell/master
Fix request.send not resolving
<DFF> @@ -501,6 +501,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
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();
});
| 13 | Merge pull request #246 from michaelpinnell/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
746 | <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;
}
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
cb(undefined, result);
}
} catch (err) {
cb(err);
}
};
}
this.push(null);
};
return stream;
}
};
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> Add on method to request object
Since there was no on method and the following error occurred
```
TypeError: request.on is not a function
```
Reference:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html
<DFF> @@ -150,6 +150,8 @@ function mockServiceMethod(service, client, method, replace) {
this.push(null);
};
return stream;
+ },
+ on: function(eventName, callback) {
}
};
| 2 | Add on method to request object | 0 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
747 | <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;
}
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
cb(undefined, result);
}
} catch (err) {
cb(err);
}
};
}
this.push(null);
};
return stream;
}
};
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> Add on method to request object
Since there was no on method and the following error occurred
```
TypeError: request.on is not a function
```
Reference:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Request.html
<DFF> @@ -150,6 +150,8 @@ function mockServiceMethod(service, client, method, replace) {
this.push(null);
};
return stream;
+ },
+ on: function(eventName, callback) {
}
};
| 2 | Add on method to request object | 0 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
748 | <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();
});
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
t.test('should mock services with required configurations', function(st){
awsMock.mock('CloudSearchDomain', 'search', 'searchString', {
endpoint: 'mockEndpoint'
});
var csd = new AWS.CloudSearchDomain();
csd.search({}, function (err, data) {
st.equals(data, 'searchString');
awsMock.restore('CloudSearchDomain');
st.end();
});
})
t.end();
});
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> Merge pull request #14 from dwyl/constructor-parameters
Refactored code to use config parameters from the real constructor
<DFF> @@ -116,17 +116,29 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
- t.test('should mock services with required configurations', function(st){
- awsMock.mock('CloudSearchDomain', 'search', 'searchString', {
- endpoint: 'mockEndpoint'
+ 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');
});
- var csd = new AWS.CloudSearchDomain();
- csd.search({}, function (err, data) {
- st.equals(data, 'searchString');
- awsMock.restore('CloudSearchDomain');
- st.end();
+ var 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.equals(data, 'message');
+ });
+
+ csd.suggest({}, function(err, data) {
+ st.equals(data, 'message');
+ });
+ st.end();
})
t.end();
});
| 20 | Merge pull request #14 from dwyl/constructor-parameters | 8 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
749 | <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();
});
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
t.test('should mock services with required configurations', function(st){
awsMock.mock('CloudSearchDomain', 'search', 'searchString', {
endpoint: 'mockEndpoint'
});
var csd = new AWS.CloudSearchDomain();
csd.search({}, function (err, data) {
st.equals(data, 'searchString');
awsMock.restore('CloudSearchDomain');
st.end();
});
})
t.end();
});
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> Merge pull request #14 from dwyl/constructor-parameters
Refactored code to use config parameters from the real constructor
<DFF> @@ -116,17 +116,29 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
- t.test('should mock services with required configurations', function(st){
- awsMock.mock('CloudSearchDomain', 'search', 'searchString', {
- endpoint: 'mockEndpoint'
+ 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');
});
- var csd = new AWS.CloudSearchDomain();
- csd.search({}, function (err, data) {
- st.equals(data, 'searchString');
- awsMock.restore('CloudSearchDomain');
- st.end();
+ var 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.equals(data, 'message');
+ });
+
+ csd.suggest({}, function(err, data) {
+ st.equals(data, 'message');
+ });
+ st.end();
})
t.end();
});
| 20 | Merge pull request #14 from dwyl/constructor-parameters | 8 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
750 | <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
awsMock.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> Merge pull request #234 from nkhil/patch-1
Update README.md
<DFF> @@ -59,7 +59,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){
AWS.mock('SNS', 'publish', 'test-message');
// S3 getObject mock - return a Buffer object with file data
-awsMock.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));
+AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));
/**
| 1 | Merge pull request #234 from nkhil/patch-1 | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
751 | <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
awsMock.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> Merge pull request #234 from nkhil/patch-1
Update README.md
<DFF> @@ -59,7 +59,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){
AWS.mock('SNS', 'publish', 'test-message');
// S3 getObject mock - return a Buffer object with file data
-awsMock.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));
+AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));
/**
| 1 | Merge pull request #234 from nkhil/patch-1 | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
752 | <NME> index.test.js
<BEF> 'use strict';
var AWS = require('aws-sdk');
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('Mocked method returns string', function(st){
awsMock.mock('SNS', 'publish', 'message');
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
const jest = require('jest-mock');
const sinon = require('sinon');
st.end();
})
});
t.test('Mocked method returns replaced function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
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();
st.end();
})
})
t.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> Updates helper functions and adds tests
Need to fix last three tests for full coverage
<DFF> @@ -3,7 +3,7 @@ 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('Mocked method returns string', function(st){
+ 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){
@@ -12,7 +12,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
})
});
- t.test('Mocked method returns replaced function', function(st){
+ t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
@@ -23,5 +23,45 @@ test('AWS.mock function should mock AWS service and method on the service', func
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.restore('SNS');
+ // st.end();
+ // })
+ // t.test('only the method on the service is restored', function(st){
+ // awsMock.restore('SNS', 'publish');
+ // st.end();
+ // })
+ // t.test('all the services are restored', function(st){
+ // awsMock.restore('SNS', 'publish');
+ // st.end();
+ // })
t.end();
});
| 42 | Updates helper functions and adds tests | 2 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
753 | <NME> index.test.js
<BEF> 'use strict';
var AWS = require('aws-sdk');
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('Mocked method returns string', function(st){
awsMock.mock('SNS', 'publish', 'message');
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
const jest = require('jest-mock');
const sinon = require('sinon');
st.end();
})
});
t.test('Mocked method returns replaced function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
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();
st.end();
})
})
t.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> Updates helper functions and adds tests
Need to fix last three tests for full coverage
<DFF> @@ -3,7 +3,7 @@ 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('Mocked method returns string', function(st){
+ 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){
@@ -12,7 +12,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
})
});
- t.test('Mocked method returns replaced function', function(st){
+ t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
@@ -23,5 +23,45 @@ test('AWS.mock function should mock AWS service and method on the service', func
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.restore('SNS');
+ // st.end();
+ // })
+ // t.test('only the method on the service is restored', function(st){
+ // awsMock.restore('SNS', 'publish');
+ // st.end();
+ // })
+ // t.test('all the services are restored', function(st){
+ // awsMock.restore('SNS', 'publish');
+ // st.end();
+ // })
t.end();
});
| 42 | Updates helper functions and adds tests | 2 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
754 | <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) };
});
st.end();
})
t.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');
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 pull request #27 from dwyl/return_stub
Return stub
<DFF> @@ -233,5 +233,10 @@ 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();
});
| 5 | Merge pull request #27 from dwyl/return_stub | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
755 | <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) };
});
st.end();
})
t.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');
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 pull request #27 from dwyl/return_stub
Return stub
<DFF> @@ -233,5 +233,10 @@ 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();
});
| 5 | Merge pull request #27 from dwyl/return_stub | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
756 | <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.end();
});
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> Merge pull request #26 from SuccessEtcllc/master
Adds method to change aws-sdk to be mocked
<DFF> @@ -240,3 +240,26 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+});
| 23 | Merge pull request #26 from SuccessEtcllc/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
757 | <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.end();
});
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> Merge pull request #26 from SuccessEtcllc/master
Adds method to change aws-sdk to be mocked
<DFF> @@ -240,3 +240,26 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+});
| 23 | Merge pull request #26 from SuccessEtcllc/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
758 | <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) => {
let result;
try {
result = replace(params);
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
// 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> replace "let result" with "const result" as per @abetomo review comment https://github.com/dwyl/aws-sdk-mock/pull/253/files#r760754733
<DFF> @@ -122,9 +122,8 @@ function wrapTestStubReplaceFn(replace) {
}
return (params, cb) => {
- let result;
try {
- result = replace(params);
+ const result = replace(params);
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
| 1 | replace "let result" with "const result" as per @abetomo review comment https://github.com/dwyl/aws-sdk-mock/pull/253/files#r760754733 | 2 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
759 | <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) => {
let result;
try {
result = replace(params);
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
// 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> replace "let result" with "const result" as per @abetomo review comment https://github.com/dwyl/aws-sdk-mock/pull/253/files#r760754733
<DFF> @@ -122,9 +122,8 @@ function wrapTestStubReplaceFn(replace) {
}
return (params, cb) => {
- let result;
try {
- result = replace(params);
+ const result = replace(params);
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
| 1 | replace "let result" with "const result" as per @abetomo review comment https://github.com/dwyl/aws-sdk-mock/pull/253/files#r760754733 | 2 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
760 | <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();
});
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
t.end();
});
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 test for config parameter
<DFF> @@ -116,5 +116,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
+ t.test('should mock services with required configurations', function(st){
+ awsMock.mock('CloudSearchDomain', 'search', 'searchString', {
+ endpoint: 'mockEndpoint'
+ });
+ var csd = new AWS.CloudSearchDomain();
+
+ csd.search({}, function (err, data) {
+ st.equals(data, 'searchString');
+ awsMock.restore('CloudSearchDomain');
+ st.end();
+ });
+ })
t.end();
});
| 12 | add test for config parameter | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
761 | <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();
});
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
t.end();
});
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 test for config parameter
<DFF> @@ -116,5 +116,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
+ t.test('should mock services with required configurations', function(st){
+ awsMock.mock('CloudSearchDomain', 'search', 'searchString', {
+ endpoint: 'mockEndpoint'
+ });
+ var csd = new AWS.CloudSearchDomain();
+
+ csd.search({}, function (err, data) {
+ st.equals(data, 'searchString');
+ awsMock.restore('CloudSearchDomain');
+ st.end();
+ });
+ })
t.end();
});
| 12 | add test for config parameter | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
762 | <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) };
});
st.end();
})
t.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');
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> Sinon stub gets returned when creating a mock
<DFF> @@ -233,5 +233,10 @@ 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();
});
| 5 | Sinon stub gets returned when creating a mock | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
763 | <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) };
});
st.end();
})
t.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');
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> Sinon stub gets returned when creating a mock
<DFF> @@ -233,5 +233,10 @@ 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();
});
| 5 | Sinon stub gets returned when creating a mock | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
764 | <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 `region not defined 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 #275 from domengabrovsek/main
Update README.md
<DFF> @@ -145,7 +145,7 @@ const expectedParams = {
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.
+**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:
| 1 | Merge pull request #275 from domengabrovsek/main | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
765 | <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 `region not defined 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 #275 from domengabrovsek/main
Update README.md
<DFF> @@ -145,7 +145,7 @@ const expectedParams = {
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.
+**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:
| 1 | Merge pull request #275 from domengabrovsek/main | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
766 | <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);
});
});
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.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 #170 from psaxton/issues/169
Allow constructors with more than 1 parameter to be mocked
<DFF> @@ -491,6 +491,14 @@ 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');
+ st.ok(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() {
| 8 | Merge pull request #170 from psaxton/issues/169 | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
767 | <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);
});
});
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.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 #170 from psaxton/issues/169
Allow constructors with more than 1 parameter to be mocked
<DFF> @@ -491,6 +491,14 @@ 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');
+ st.ok(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() {
| 8 | Merge pull request #170 from psaxton/issues/169 | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
768 | <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 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> Adds test and scripts for testing and coverage
<DFF> @@ -0,0 +1,15 @@
+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('Mocked method returns data', function(st){
+ awsMock.mock('SNS', 'publish', 'message');
+ var sns = new AWS.SNS();
+ sns.publish({}, function(err, data){
+ st.equals(data, 'message');
+ st.end()
+ })
+ })
+ t.end();
+});
| 15 | Adds test and scripts for testing and coverage | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
769 | <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 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> Adds test and scripts for testing and coverage
<DFF> @@ -0,0 +1,15 @@
+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('Mocked method returns data', function(st){
+ awsMock.mock('SNS', 'publish', 'message');
+ var sns = new AWS.SNS();
+ sns.publish({}, function(err, data){
+ st.equals(data, 'message');
+ st.end()
+ })
+ })
+ t.end();
+});
| 15 | Adds test and scripts for testing and coverage | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
770 | <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
}
```
Example:
```js
var path = require('path');
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
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 #116 from jkimau/update-readme
remove unnecessary line from a exmaple in README
<DFF> @@ -173,7 +173,6 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec
Example:
```js
-var path = require('path');
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
| 0 | Merge pull request #116 from jkimau/update-readme | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
771 | <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
}
```
Example:
```js
var path = require('path');
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
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 #116 from jkimau/update-readme
remove unnecessary line from a exmaple in README
<DFF> @@ -173,7 +173,6 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec
Example:
```js
-var path = require('path');
var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
| 0 | Merge pull request #116 from jkimau/update-readme | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
772 | <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;
AWS.config.paramValidation = false;
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');
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
st.end();
});
});
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
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();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
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'});
var s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
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');
var s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, '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});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
st.equal(data.Body, 'body');
st.end();
});
});
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.equal(data, 'message');
st.end();
});
});
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.equal(data, 'test');
st.end();
});
});
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
var 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');
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) {
sns1.subscribe({}, function(err, data){
st.equal(data, 'message 2');
});
if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
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(){
lambda.getFunction({}, function(err, data) {
st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equal(data, 'message');
});
});
t.test('replacement returns thennable', function(st){
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(){
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('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
var S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
var 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);
});
var lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
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) {});
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;
}
});
}
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');
var s3 = new AWS.S3();
var req = s3.getObject('getObject', function(err, data) {});
st.ok(isNodeStream(req.createReadStream()));
// with or without callback
req = s3.getObject('getObject');
self.value = value;
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
var bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
var stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
st.ok(isNodeStream(req.createReadStream()));
});
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');
st.end();
}));
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, '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');
st.end();
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(), '');
st.end();
const stream = new AWS.S3().getObject('getObject').createReadStream();
});
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(), '');
st.end();
const stream = req.createReadStream();
});
t.test('call on 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.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('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'});
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);
});
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');
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.equals(AWS.SNS.isSinonProxy, true);
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
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');
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
var docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
});
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);
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);
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');
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');
var docClient = new AWS.DynamoDB.DocumentClient();
var dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
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){
return callback(null, 'message');
});
var csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
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});
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
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');
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');
st.end();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.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(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();
});
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');
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');
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 #208 from abetomo/feature/replace_var_with_const
Replace 'var' with 'const' or 'let'
<DFF> @@ -1,10 +1,12 @@
-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;
+'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;
@@ -16,7 +18,7 @@ tap.afterEach(function (done) {
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();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
@@ -26,7 +28,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
@@ -34,7 +36,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
- var s3 = new AWS.S3();
+ const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
@@ -48,7 +50,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
- var s3 = new AWS.S3({paramValidation: true});
+ const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
@@ -57,7 +59,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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});
+ const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
st.end();
@@ -65,7 +67,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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});
+ const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
@@ -76,7 +78,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
@@ -89,7 +91,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'test');
});
@@ -102,7 +104,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
@@ -118,7 +120,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equals(data, 'message');
lambda.createFunction({}, function(err, data) {
@@ -129,14 +131,14 @@ 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){
- var error = new Error('on purpose');
+ 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');
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
@@ -147,14 +149,14 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
t.test('replacement returns thennable', function(st){
- var error = new Error('on purpose');
+ 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)
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
@@ -172,19 +174,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
- var S3 = new AWS.S3();
+ const S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
- var error = new Error('on purpose');
+ 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);
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
@@ -198,9 +200,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
function P(handler) {
- var self = this;
+ const self = this;
function yay (value) {
self.value = value;
}
@@ -208,7 +210,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
- var promise = lambda.getFunction({}).promise();
+ const promise = lambda.getFunction({}).promise();
st.equals(promise.constructor.name, 'P');
promise.then(function(data) {
st.equals(data, 'message');
@@ -218,8 +220,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
- var s3 = new AWS.S3();
- var req = s3.getObject('getObject', function(err, data) {});
+ 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');
@@ -227,17 +229,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
- var stream = req.createReadStream();
+ const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
- var bodyStream = new Readable();
+ const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
- var stream = new AWS.S3().getObject('getObject').createReadStream();
+ const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
@@ -245,9 +247,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
@@ -255,9 +257,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
- var s3 = new AWS.S3();
- var req = s3.getObject('getObject', {});
- var stream = req.createReadStream();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
@@ -265,9 +267,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
st.end();
@@ -275,9 +277,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
st.end();
@@ -285,15 +287,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('call on method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
- var s3 = new AWS.S3();
- var req = s3.getObject('getObject', {});
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
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', {});
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
st.equals(typeof req.send, 'function');
st.end();
});
@@ -312,7 +314,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
st.equals(sns.publish.isSinonProxy, true);
@@ -332,9 +334,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
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();
+ const sns = new AWS.SNS();
+ const docClient = new AWS.DynamoDB.DocumentClient();
+ const dynamoDb = new AWS.DynamoDB();
st.equals(AWS.SNS.isSinonProxy, true);
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
@@ -355,7 +357,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
- var docClient = new AWS.DynamoDB.DocumentClient();
+ const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
@@ -387,7 +389,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
- var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
+ const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.query.isSinonProxy, true);
@@ -400,8 +402,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
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');
- var docClient = new AWS.DynamoDB.DocumentClient();
- var dynamoDb = new AWS.DynamoDB();
+ const docClient = new AWS.DynamoDB.DocumentClient();
+ let dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
@@ -443,7 +445,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
return callback(null, 'message');
});
- var csd = new AWS.CloudSearchDomain({
+ const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
@@ -463,7 +465,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
- var stub = awsMock.mock('CloudSearchDomain', 'search');
+ const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
st.end();
});
@@ -484,7 +486,7 @@ 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();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
@@ -494,7 +496,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');
+ const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
@@ -512,10 +514,10 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
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');
+ const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message2');
st.end();
@@ -523,7 +525,7 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
- var bad = {};
+ const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
| 65 | Merge pull request #208 from abetomo/feature/replace_var_with_const | 63 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
773 | <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;
AWS.config.paramValidation = false;
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');
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
st.end();
});
});
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
var sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
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();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
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'});
var s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
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');
var s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, '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});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
st.equal(data.Body, 'body');
st.end();
});
});
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.equal(data, 'message');
st.end();
});
});
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.equal(data, 'test');
st.end();
});
});
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
var 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');
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) {
sns1.subscribe({}, function(err, data){
st.equal(data, 'message 2');
});
if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
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(){
lambda.getFunction({}, function(err, data) {
st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equal(data, 'message');
});
});
t.test('replacement returns thennable', function(st){
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(){
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('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
var S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
var 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);
});
var lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
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) {});
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;
}
});
}
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');
var s3 = new AWS.S3();
var req = s3.getObject('getObject', function(err, data) {});
st.ok(isNodeStream(req.createReadStream()));
// with or without callback
req = s3.getObject('getObject');
self.value = value;
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
var bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
var stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
st.ok(isNodeStream(req.createReadStream()));
});
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');
st.end();
}));
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, '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');
st.end();
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(), '');
st.end();
const stream = new AWS.S3().getObject('getObject').createReadStream();
});
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(), '');
st.end();
const stream = req.createReadStream();
});
t.test('call on 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.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('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'});
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);
});
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');
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.equals(AWS.SNS.isSinonProxy, true);
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
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');
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
var docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
});
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);
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);
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');
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');
var docClient = new AWS.DynamoDB.DocumentClient();
var dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
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){
return callback(null, 'message');
});
var csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
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});
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
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');
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');
st.end();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.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(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();
});
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');
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');
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 #208 from abetomo/feature/replace_var_with_const
Replace 'var' with 'const' or 'let'
<DFF> @@ -1,10 +1,12 @@
-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;
+'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;
@@ -16,7 +18,7 @@ tap.afterEach(function (done) {
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();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
@@ -26,7 +28,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
@@ -34,7 +36,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
- var s3 = new AWS.S3();
+ const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
@@ -48,7 +50,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
- var s3 = new AWS.S3({paramValidation: true});
+ const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
@@ -57,7 +59,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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});
+ const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equals(data, 'message');
st.end();
@@ -65,7 +67,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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});
+ const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
@@ -76,7 +78,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
@@ -89,7 +91,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'test');
});
@@ -102,7 +104,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
@@ -118,7 +120,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equals(data, 'message');
lambda.createFunction({}, function(err, data) {
@@ -129,14 +131,14 @@ 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){
- var error = new Error('on purpose');
+ 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');
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
@@ -147,14 +149,14 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
t.test('replacement returns thennable', function(st){
- var error = new Error('on purpose');
+ 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)
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
@@ -172,19 +174,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
- var S3 = new AWS.S3();
+ const S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
- var error = new Error('on purpose');
+ 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);
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
@@ -198,9 +200,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
- var lambda = new AWS.Lambda();
+ const lambda = new AWS.Lambda();
function P(handler) {
- var self = this;
+ const self = this;
function yay (value) {
self.value = value;
}
@@ -208,7 +210,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
- var promise = lambda.getFunction({}).promise();
+ const promise = lambda.getFunction({}).promise();
st.equals(promise.constructor.name, 'P');
promise.then(function(data) {
st.equals(data, 'message');
@@ -218,8 +220,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
- var s3 = new AWS.S3();
- var req = s3.getObject('getObject', function(err, data) {});
+ 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');
@@ -227,17 +229,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
- var stream = req.createReadStream();
+ const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
- var bodyStream = new Readable();
+ const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
- var stream = new AWS.S3().getObject('getObject').createReadStream();
+ const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
@@ -245,9 +247,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
@@ -255,9 +257,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
- var s3 = new AWS.S3();
- var req = s3.getObject('getObject', {});
- var stream = req.createReadStream();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), 'body');
st.end();
@@ -265,9 +267,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
st.end();
@@ -275,9 +277,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
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();
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
+ const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '');
st.end();
@@ -285,15 +287,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('call on method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
- var s3 = new AWS.S3();
- var req = s3.getObject('getObject', {});
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
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', {});
+ const s3 = new AWS.S3();
+ const req = s3.getObject('getObject', {});
st.equals(typeof req.send, 'function');
st.end();
});
@@ -312,7 +314,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
st.equals(sns.publish.isSinonProxy, true);
@@ -332,9 +334,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
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();
+ const sns = new AWS.SNS();
+ const docClient = new AWS.DynamoDB.DocumentClient();
+ const dynamoDb = new AWS.DynamoDB();
st.equals(AWS.SNS.isSinonProxy, true);
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
@@ -355,7 +357,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
- var docClient = new AWS.DynamoDB.DocumentClient();
+ const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
@@ -387,7 +389,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
- var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
+ const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.query.isSinonProxy, true);
@@ -400,8 +402,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
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');
- var docClient = new AWS.DynamoDB.DocumentClient();
- var dynamoDb = new AWS.DynamoDB();
+ const docClient = new AWS.DynamoDB.DocumentClient();
+ let dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
@@ -443,7 +445,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
return callback(null, 'message');
});
- var csd = new AWS.CloudSearchDomain({
+ const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
@@ -463,7 +465,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
- var stub = awsMock.mock('CloudSearchDomain', 'search');
+ const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
st.end();
});
@@ -484,7 +486,7 @@ 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();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message');
st.end();
@@ -494,7 +496,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');
+ const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
@@ -512,10 +514,10 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
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');
+ const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
- var sns = new AWS.SNS();
+ const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equals(data, 'message2');
st.end();
@@ -523,7 +525,7 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
- var bad = {};
+ const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
| 65 | Merge pull request #208 from abetomo/feature/replace_var_with_const | 63 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
774 | <NME> index.js
<BEF> var sinon = require('sinon');
var aws = require('aws-sdk');
var core = {};
var AWS = {};
AWS.mock = function(service, method, replace) {
core[service] = {};
core[service].awsConstructor = aws[service];
mockService(service, method, replace);
}
function mockService(service, method, replace) {
var serviceStub = sinon.stub(aws, service, function() {
var client = new core[service].awsConstructor();
client.sandbox = sinon.sandbox.create();
core[service].client = client;
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;
}
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> Updates readme with examples
<DFF> @@ -1,17 +1,17 @@
var sinon = require('sinon');
-var aws = require('aws-sdk');
+var _AWS = require('aws-sdk');
var core = {};
var AWS = {};
AWS.mock = function(service, method, replace) {
core[service] = {};
- core[service].awsConstructor = aws[service];
+ core[service].awsConstructor = _AWS[service];
mockService(service, method, replace);
}
function mockService(service, method, replace) {
- var serviceStub = sinon.stub(aws, service, function() {
+ var serviceStub = sinon.stub(_AWS, service, function() {
var client = new core[service].awsConstructor();
client.sandbox = sinon.sandbox.create();
core[service].client = client;
| 3 | Updates readme with examples | 3 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
775 | <NME> index.js
<BEF> var sinon = require('sinon');
var aws = require('aws-sdk');
var core = {};
var AWS = {};
AWS.mock = function(service, method, replace) {
core[service] = {};
core[service].awsConstructor = aws[service];
mockService(service, method, replace);
}
function mockService(service, method, replace) {
var serviceStub = sinon.stub(aws, service, function() {
var client = new core[service].awsConstructor();
client.sandbox = sinon.sandbox.create();
core[service].client = client;
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;
}
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> Updates readme with examples
<DFF> @@ -1,17 +1,17 @@
var sinon = require('sinon');
-var aws = require('aws-sdk');
+var _AWS = require('aws-sdk');
var core = {};
var AWS = {};
AWS.mock = function(service, method, replace) {
core[service] = {};
- core[service].awsConstructor = aws[service];
+ core[service].awsConstructor = _AWS[service];
mockService(service, method, replace);
}
function mockService(service, method, replace) {
- var serviceStub = sinon.stub(aws, service, function() {
+ var serviceStub = sinon.stub(_AWS, service, function() {
var client = new core[service].awsConstructor();
client.sandbox = sinon.sandbox.create();
core[service].client = client;
| 3 | Updates readme with examples | 3 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
776 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
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');
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) {
});
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "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> feat: validate service method params if config.paramValidation is set
BREAKING CHANGE: Since the default for `AWS.config.paramValidation` is true, this may break currently passing tests until they're updated, either with `paramValidation=false` or with actually correct inputs.
<DFF> @@ -4,6 +4,8 @@ var AWS = require('aws-sdk');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
+AWS.config.paramValidation = false;
+
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');
@@ -40,6 +42,24 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
});
+ t.test('method fails on invalid input if paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var 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 succeeds on valid input when paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var s3 = new AWS.S3({paramValidation: true});
+ s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
+ st.notOk(err);
+ st.equals(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");
| 20 | feat: validate service method params if config.paramValidation is set | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
777 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
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');
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) {
});
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "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> feat: validate service method params if config.paramValidation is set
BREAKING CHANGE: Since the default for `AWS.config.paramValidation` is true, this may break currently passing tests until they're updated, either with `paramValidation=false` or with actually correct inputs.
<DFF> @@ -4,6 +4,8 @@ var AWS = require('aws-sdk');
var isNodeStream = require('is-node-stream');
var concatStream = require('concat-stream');
+AWS.config.paramValidation = false;
+
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');
@@ -40,6 +42,24 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
});
+ t.test('method fails on invalid input if paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var 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 succeeds on valid input when paramValidation is set', function(st) {
+ awsMock.mock('S3', 'getObject', {Body: 'body'});
+ var s3 = new AWS.S3({paramValidation: true});
+ s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
+ st.notOk(err);
+ st.equals(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");
| 20 | feat: validate service method params if config.paramValidation is set | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
778 | <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;
}
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);
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
services[service].methodMocks[method].stub.restore();
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
}
}
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 #37 from motiz88/motiz88-patch-1
Avoid stub.restore() in restoreMethod if !stub
<DFF> @@ -179,7 +179,9 @@ function restoreAllMethods(service) {
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
- services[service].methodMocks[method].stub.restore();
+ if (services[service].methodMocks[method].stub) {
+ services[service].methodMocks[method].stub.restore();
+ }
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
| 3 | Merge pull request #37 from motiz88/motiz88-patch-1 | 1 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
779 | <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;
}
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);
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
services[service].methodMocks[method].stub.restore();
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
}
}
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 #37 from motiz88/motiz88-patch-1
Avoid stub.restore() in restoreMethod if !stub
<DFF> @@ -179,7 +179,9 @@ function restoreAllMethods(service) {
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
- services[service].methodMocks[method].stub.restore();
+ if (services[service].methodMocks[method].stub) {
+ services[service].methodMocks[method].stub.restore();
+ }
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
| 3 | Merge pull request #37 from motiz88/motiz88-patch-1 | 1 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
780 | <NME> index.test.js
<BEF> 'use strict';
var AWS = require('aws-sdk');
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('Mocked method returns data', 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('Unmocked method should work as normal', function(st) {
awsMock.mock('SNS', 'publish', 'message');
var sns = new AWS.SNS();
sns.subscribe({}, function (err, data) {
console.log(err);
console.log(data);
st.end();
});
})
t.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> Adds test to replace a method with a function
<DFF> @@ -3,23 +3,34 @@ 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('Mocked method returns data', function(st){
+ t.test('Mocked method returns 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()
+ st.end();
})
- })
- t.test('Unmocked method should work as normal', function(st) {
- awsMock.mock('SNS', 'publish', 'message');
+ });
+ t.test('Mocked method returns replaced function', function(st){
+ awsMock.mock('SNS', 'publish', function(params, callback){
+ callback(null, "message");
+ });
var sns = new AWS.SNS();
- sns.subscribe({}, function (err, data) {
- console.log(err);
- console.log(data);
+ sns.publish({}, function(err, data){
+ st.equals(data, 'message');
+ awsMock.restore('SNS');
st.end();
- });
+ })
})
+ // t.test('Unmocked method should work as normal', function(st) {
+ // awsMock.mock('SNS', 'publish', 'message');
+ // var sns = new AWS.SNS();
+ // sns.subscribe({}, function (err, data) {
+ // console.log(err);
+ // console.log(data);
+ // st.end();
+ // });
+ // })
t.end();
});
| 20 | Adds test to replace a method with a function | 9 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
781 | <NME> index.test.js
<BEF> 'use strict';
var AWS = require('aws-sdk');
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('Mocked method returns data', 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('Unmocked method should work as normal', function(st) {
awsMock.mock('SNS', 'publish', 'message');
var sns = new AWS.SNS();
sns.subscribe({}, function (err, data) {
console.log(err);
console.log(data);
st.end();
});
})
t.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> Adds test to replace a method with a function
<DFF> @@ -3,23 +3,34 @@ 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('Mocked method returns data', function(st){
+ t.test('Mocked method returns 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()
+ st.end();
})
- })
- t.test('Unmocked method should work as normal', function(st) {
- awsMock.mock('SNS', 'publish', 'message');
+ });
+ t.test('Mocked method returns replaced function', function(st){
+ awsMock.mock('SNS', 'publish', function(params, callback){
+ callback(null, "message");
+ });
var sns = new AWS.SNS();
- sns.subscribe({}, function (err, data) {
- console.log(err);
- console.log(data);
+ sns.publish({}, function(err, data){
+ st.equals(data, 'message');
+ awsMock.restore('SNS');
st.end();
- });
+ })
})
+ // t.test('Unmocked method should work as normal', function(st) {
+ // awsMock.mock('SNS', 'publish', 'message');
+ // var sns = new AWS.SNS();
+ // sns.subscribe({}, function (err, data) {
+ // console.log(err);
+ // console.log(data);
+ // st.end();
+ // });
+ // })
t.end();
});
| 20 | Adds test to replace a method with a function | 9 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
782 | <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.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
st.end();
});
});
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');
req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
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> Merge pull request #50 from MrHen/feature/createReadStream-payloads
Add createReadStream payload support
<DFF> @@ -48,6 +48,7 @@ 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();
});
});
@@ -57,6 +58,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 +183,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();
}));
});
| 47 | Merge pull request #50 from MrHen/feature/createReadStream-payloads | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
783 | <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.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
st.end();
});
});
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');
req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
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> Merge pull request #50 from MrHen/feature/createReadStream-payloads
Add createReadStream payload support
<DFF> @@ -48,6 +48,7 @@ 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();
});
});
@@ -57,6 +58,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 +183,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();
}));
});
| 47 | Merge pull request #50 from MrHen/feature/createReadStream-payloads | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
784 | <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.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
st.end();
});
});
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');
req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
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 createReadStream payload support
<DFF> @@ -48,6 +48,7 @@ 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();
});
});
@@ -57,6 +58,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 +183,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();
}));
});
| 47 | Add createReadStream payload support | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
785 | <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.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equals(data.Body, 'body');
st.end();
});
});
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');
req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
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 createReadStream payload support
<DFF> @@ -48,6 +48,7 @@ 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();
});
});
@@ -57,6 +58,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 +183,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();
}));
});
| 47 | Add createReadStream payload support | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
786 | <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);
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
var sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
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();
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
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 unused variables
<DFF> @@ -263,7 +263,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
- var sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
@@ -434,7 +433,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
- var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
| 0 | Remove unused variables | 2 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
787 | <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);
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
var sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
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();
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
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 unused variables
<DFF> @@ -263,7 +263,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
- var sns = new AWS.SNS();
st.equals(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
@@ -434,7 +433,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
- var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
| 0 | Remove unused variables | 2 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
788 | <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'}});
});
```
**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';
### 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
### 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> Update README.md
<DFF> @@ -270,7 +270,7 @@ const sqs = new AWS.SQS();
### 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.
+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
| 1 | Update README.md | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
789 | <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'}});
});
```
**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';
### 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
### 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> Update README.md
<DFF> @@ -270,7 +270,7 @@ const sqs = new AWS.SQS();
### 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.
+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
| 1 | Update README.md | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
790 | <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> 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 | Fix wrong TypeScript definitions | 4 | .ts | d | apache-2.0 | dwyl/aws-sdk-mock |
791 | <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> 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 | Fix wrong TypeScript definitions | 4 | .ts | d | apache-2.0 | dwyl/aws-sdk-mock |
792 | <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();
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");
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> Modified mock method to handle mocking AWS services whose signatures are different from (params, callback).
<DFF> @@ -23,6 +23,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
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();
+ s3.getSignedUrl('getObject', {}, function(err, data) {
+ st.equals(data, 'message');
+ awsMock.mock('S3', 'upload', function(params, options, callback) {
+ callback(null, options);
+ });
+ s3.upload({}, {test: 'message'}, function(err, data) {
+ st.equals(data.test, 'message');
+ awsMock.restore('S3');
+ 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");
| 15 | Modified mock method to handle mocking AWS services whose signatures are different from (params, callback). | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
793 | <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();
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");
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> Modified mock method to handle mocking AWS services whose signatures are different from (params, callback).
<DFF> @@ -23,6 +23,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
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();
+ s3.getSignedUrl('getObject', {}, function(err, data) {
+ st.equals(data, 'message');
+ awsMock.mock('S3', 'upload', function(params, options, callback) {
+ callback(null, options);
+ });
+ s3.upload({}, {test: 'message'}, function(err, data) {
+ st.equals(data.test, 'message');
+ awsMock.restore('S3');
+ 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");
| 15 | Modified mock method to handle mocking AWS services whose signatures are different from (params, callback). | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
794 | <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> Fix "Why" header in readme
Seems like some invisible character was preventing the header from rendering correctly on Github.
<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 | Fix "Why" header in readme | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
795 | <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> Fix "Why" header in readme
Seems like some invisible character was preventing the header from rendering correctly on Github.
<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 | Fix "Why" header in readme | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
796 | <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');
});
});
});
});
if (typeof(Promise) === 'function') {
t.test('promises are supported', function(st){
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
});
});
});
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> Update 'space-unary-ops' of eslint
Unify the style of `typeof` etc.
https://eslint.org/docs/rules/space-unary-ops
<DFF> @@ -127,7 +127,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
});
- if (typeof(Promise) === 'function') {
+ if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
| 1 | Update 'space-unary-ops' of eslint | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
797 | <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');
});
});
});
});
if (typeof(Promise) === 'function') {
t.test('promises are supported', function(st){
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
});
});
});
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> Update 'space-unary-ops' of eslint
Unify the style of `typeof` etc.
https://eslint.org/docs/rules/space-unary-ops
<DFF> @@ -127,7 +127,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
});
- if (typeof(Promise) === 'function') {
+ if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
var error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
| 1 | Update 'space-unary-ops' of eslint | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
798 | <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
var AWS = require('aws-sdk-mock');
AWS.mock('DynamoDB', 'putItem', function (params, callback){
callback(null, "successfully put item in database");
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
```
```typescript
import * as AWSMock from "aws-sdk-mock";
import * as AWS from "aws-sdk";
import { GetItemInput } from "aws-sdk/clients/dynamodb";
beforeAll(async (done) => {
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) => {
callback(null, {pk: "foo", sk: "bar"});
})
let 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) => {
callback(null, {pk: "foo", sk: "bar"});
})
let 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');
});
});
```
You can also pass Sinon spies to the mock:
```js
var updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
// Object under test
// 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,
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters');
```
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
exports.handler = function(event, context) {
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
}
```
const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
}
```
```js
exports.handler = function(event, context) {
someAsyncFunction(() => {
var sns = AWS.SNS();
var dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
});
}
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
Example 2 (will work):
```js
exports.handler = function(event, context) {
var sns = AWS.SNS();
var dynamoDb = AWS.DynamoDB();
someAsyncFunction(() => {
// do something with the services e.g. sns.publish
});
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');
Some constructors of the aws-sdk will require you to pass through a configuration object.
```js
var csd = new AWS.CloudSearchDomain({
endpoint: 'your.end.point',
region: 'eu-west'
});
```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>
Example:
```js
var path = require('path');
var AWS = require('aws-sdk-mock');
AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
```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
Example (if Q is your promise library of choice):
```js
var AWS = require('aws-sdk-mock'),
Q = require('q');
AWS.Promise = Q.Promise;
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 #210 from abetomo/feature/update_readme
Updated README code example
<DFF> @@ -49,7 +49,7 @@ npm install aws-sdk-mock --save-dev
#### Using plain JavaScript
```js
-var AWS = require('aws-sdk-mock');
+const AWS = require('aws-sdk-mock');
AWS.mock('DynamoDB', 'putItem', function (params, callback){
callback(null, "successfully put item in database");
@@ -75,7 +75,7 @@ AWS.restore('S3');
```typescript
import * as AWSMock from "aws-sdk-mock";
-import * as AWS from "aws-sdk";
+import * as AWS from "aws-sdk";
import { GetItemInput } from "aws-sdk/clients/dynamodb";
beforeAll(async (done) => {
@@ -97,7 +97,7 @@ describe("the module", () => {
callback(null, {pk: "foo", sk: "bar"});
})
- let input:GetItemInput = { TableName: '', Key: {} };
+ 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' });
@@ -112,7 +112,7 @@ describe("the module", () => {
callback(null, {pk: "foo", sk: "bar"});
})
- let input:GetItemInput = { TableName: '', Key: {} };
+ 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' });
@@ -125,7 +125,7 @@ describe("the module", () => {
You can also pass Sinon spies to the mock:
```js
-var updateTableSpy = sinon.spy();
+const updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
// Object under test
@@ -133,7 +133,7 @@ myDynamoManager.scaleDownTable();
// Assert on your Sinon spy as normal
assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK');
-var expectedParams = {
+const expectedParams = {
TableName: 'testTableName',
ProvisionedThroughput: {
ReadCapacityUnits: 1,
@@ -147,9 +147,9 @@ assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct pa
Example 1:
```js
-var AWS = require('aws-sdk');
-var sns = AWS.SNS();
-var dynamoDb = AWS.DynamoDB();
+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
@@ -158,11 +158,11 @@ exports.handler = function(event, context) {
Example 2:
```js
-var AWS = require('aws-sdk');
+const AWS = require('aws-sdk');
exports.handler = function(event, context) {
- var sns = AWS.SNS();
- var dynamoDb = AWS.DynamoDB();
+ const sns = AWS.SNS();
+ const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
}
```
@@ -173,8 +173,8 @@ Example 1 (won't work):
```js
exports.handler = function(event, context) {
someAsyncFunction(() => {
- var sns = AWS.SNS();
- var dynamoDb = AWS.DynamoDB();
+ const sns = AWS.SNS();
+ const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
});
}
@@ -183,8 +183,8 @@ exports.handler = function(event, context) {
Example 2 (will work):
```js
exports.handler = function(event, context) {
- var sns = AWS.SNS();
- var dynamoDb = AWS.DynamoDB();
+ const sns = AWS.SNS();
+ const dynamoDb = AWS.DynamoDB();
someAsyncFunction(() => {
// do something with the services e.g. sns.publish
});
@@ -223,7 +223,7 @@ AWS.restore('DynamoDB');
Some constructors of the aws-sdk will require you to pass through a configuration object.
```js
-var csd = new AWS.CloudSearchDomain({
+const csd = new AWS.CloudSearchDomain({
endpoint: 'your.end.point',
region: 'eu-west'
});
@@ -241,8 +241,8 @@ Project structures that don't include the `aws-sdk` at the top level `node_modul
Example:
```js
-var path = require('path');
-var AWS = require('aws-sdk-mock');
+const path = require('path');
+const AWS = require('aws-sdk-mock');
AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
@@ -274,7 +274,7 @@ If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you c
Example (if Q is your promise library of choice):
```js
-var AWS = require('aws-sdk-mock'),
+const AWS = require('aws-sdk-mock'),
Q = require('q');
AWS.Promise = Q.Promise;
| 20 | Merge pull request #210 from abetomo/feature/update_readme | 20 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
799 | <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
var AWS = require('aws-sdk-mock');
AWS.mock('DynamoDB', 'putItem', function (params, callback){
callback(null, "successfully put item in database");
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
```
```typescript
import * as AWSMock from "aws-sdk-mock";
import * as AWS from "aws-sdk";
import { GetItemInput } from "aws-sdk/clients/dynamodb";
beforeAll(async (done) => {
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) => {
callback(null, {pk: "foo", sk: "bar"});
})
let 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) => {
callback(null, {pk: "foo", sk: "bar"});
})
let 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');
});
});
```
You can also pass Sinon spies to the mock:
```js
var updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
// Object under test
// 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,
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters');
```
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
exports.handler = function(event, context) {
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
}
```
const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
}
```
```js
exports.handler = function(event, context) {
someAsyncFunction(() => {
var sns = AWS.SNS();
var dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
});
}
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
Example 2 (will work):
```js
exports.handler = function(event, context) {
var sns = AWS.SNS();
var dynamoDb = AWS.DynamoDB();
someAsyncFunction(() => {
// do something with the services e.g. sns.publish
});
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');
Some constructors of the aws-sdk will require you to pass through a configuration object.
```js
var csd = new AWS.CloudSearchDomain({
endpoint: 'your.end.point',
region: 'eu-west'
});
```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>
Example:
```js
var path = require('path');
var AWS = require('aws-sdk-mock');
AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
```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
Example (if Q is your promise library of choice):
```js
var AWS = require('aws-sdk-mock'),
Q = require('q');
AWS.Promise = Q.Promise;
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 #210 from abetomo/feature/update_readme
Updated README code example
<DFF> @@ -49,7 +49,7 @@ npm install aws-sdk-mock --save-dev
#### Using plain JavaScript
```js
-var AWS = require('aws-sdk-mock');
+const AWS = require('aws-sdk-mock');
AWS.mock('DynamoDB', 'putItem', function (params, callback){
callback(null, "successfully put item in database");
@@ -75,7 +75,7 @@ AWS.restore('S3');
```typescript
import * as AWSMock from "aws-sdk-mock";
-import * as AWS from "aws-sdk";
+import * as AWS from "aws-sdk";
import { GetItemInput } from "aws-sdk/clients/dynamodb";
beforeAll(async (done) => {
@@ -97,7 +97,7 @@ describe("the module", () => {
callback(null, {pk: "foo", sk: "bar"});
})
- let input:GetItemInput = { TableName: '', Key: {} };
+ 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' });
@@ -112,7 +112,7 @@ describe("the module", () => {
callback(null, {pk: "foo", sk: "bar"});
})
- let input:GetItemInput = { TableName: '', Key: {} };
+ 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' });
@@ -125,7 +125,7 @@ describe("the module", () => {
You can also pass Sinon spies to the mock:
```js
-var updateTableSpy = sinon.spy();
+const updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
// Object under test
@@ -133,7 +133,7 @@ myDynamoManager.scaleDownTable();
// Assert on your Sinon spy as normal
assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK');
-var expectedParams = {
+const expectedParams = {
TableName: 'testTableName',
ProvisionedThroughput: {
ReadCapacityUnits: 1,
@@ -147,9 +147,9 @@ assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct pa
Example 1:
```js
-var AWS = require('aws-sdk');
-var sns = AWS.SNS();
-var dynamoDb = AWS.DynamoDB();
+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
@@ -158,11 +158,11 @@ exports.handler = function(event, context) {
Example 2:
```js
-var AWS = require('aws-sdk');
+const AWS = require('aws-sdk');
exports.handler = function(event, context) {
- var sns = AWS.SNS();
- var dynamoDb = AWS.DynamoDB();
+ const sns = AWS.SNS();
+ const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
}
```
@@ -173,8 +173,8 @@ Example 1 (won't work):
```js
exports.handler = function(event, context) {
someAsyncFunction(() => {
- var sns = AWS.SNS();
- var dynamoDb = AWS.DynamoDB();
+ const sns = AWS.SNS();
+ const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
});
}
@@ -183,8 +183,8 @@ exports.handler = function(event, context) {
Example 2 (will work):
```js
exports.handler = function(event, context) {
- var sns = AWS.SNS();
- var dynamoDb = AWS.DynamoDB();
+ const sns = AWS.SNS();
+ const dynamoDb = AWS.DynamoDB();
someAsyncFunction(() => {
// do something with the services e.g. sns.publish
});
@@ -223,7 +223,7 @@ AWS.restore('DynamoDB');
Some constructors of the aws-sdk will require you to pass through a configuration object.
```js
-var csd = new AWS.CloudSearchDomain({
+const csd = new AWS.CloudSearchDomain({
endpoint: 'your.end.point',
region: 'eu-west'
});
@@ -241,8 +241,8 @@ Project structures that don't include the `aws-sdk` at the top level `node_modul
Example:
```js
-var path = require('path');
-var AWS = require('aws-sdk-mock');
+const path = require('path');
+const AWS = require('aws-sdk-mock');
AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
@@ -274,7 +274,7 @@ If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you c
Example (if Q is your promise library of choice):
```js
-var AWS = require('aws-sdk-mock'),
+const AWS = require('aws-sdk-mock'),
Q = require('q');
AWS.Promise = Q.Promise;
| 20 | Merge pull request #210 from abetomo/feature/update_readme | 20 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |