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
|
---|---|---|---|---|---|---|---|---|
600 | <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');
st.equals(data, 'message 2');
st.end();
});
});
});
t.test('multiple methods can be mocked on the same service', function(st){
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
});
if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(error, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('replacement returns thennable', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params) {
return Promise.resolve('message')
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
return Promise.reject(error)
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('no unhandled promise rejections when promises are not used', function(st) {
process.on('unhandledRejection', function(reason, promise) {
st.fail('unhandledRejection, reason follows');
st.error(reason);
});
awsMock.mock('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
const S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
setTimeout(callback.bind(this, error, 'message'), 10);
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('promises can be configured', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
function P(handler) {
const self = this;
function yay (value) {
self.value = value;
}
handler(yay, function(){});
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
st.equal(data, 'message');
st.end();
});
});
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
let req = s3.getObject('getObject', function(err, data) {});
st.ok(isNodeStream(req.createReadStream()));
// with or without callback
req = s3.getObject('getObject');
st.ok(isNodeStream(req.createReadStream()));
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with returned streams', function(st) {
awsMock.mock('S3', 'getObject', () => {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
return bodyStream;
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream ignores functions', function(st) {
awsMock.mock('S3', 'getObject', function(){});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('request object createReadStream ignores non-buffer objects', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('call on method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.on, 'function');
st.end();
});
t.test('call send method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.send, 'function');
st.end();
});
t.test('all the methods on a service are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
st.equal(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('only the method on the service is restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('method on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all methods on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> When method is restored, it should be restored on all clients
<DFF> @@ -131,7 +131,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message 2');
st.end();
});
-
});
});
t.test('multiple methods can be mocked on the same service', function(st){
| 0 | When method is restored, it should be restored on all clients | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
601 | <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');
st.equals(data, 'message 2');
st.end();
});
});
});
t.test('multiple methods can be mocked on the same service', function(st){
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
});
if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(error, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('replacement returns thennable', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params) {
return Promise.resolve('message')
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
return Promise.reject(error)
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('no unhandled promise rejections when promises are not used', function(st) {
process.on('unhandledRejection', function(reason, promise) {
st.fail('unhandledRejection, reason follows');
st.error(reason);
});
awsMock.mock('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
const S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
setTimeout(callback.bind(this, error, 'message'), 10);
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('promises can be configured', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
function P(handler) {
const self = this;
function yay (value) {
self.value = value;
}
handler(yay, function(){});
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
st.equal(data, 'message');
st.end();
});
});
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
let req = s3.getObject('getObject', function(err, data) {});
st.ok(isNodeStream(req.createReadStream()));
// with or without callback
req = s3.getObject('getObject');
st.ok(isNodeStream(req.createReadStream()));
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with returned streams', function(st) {
awsMock.mock('S3', 'getObject', () => {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
return bodyStream;
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream ignores functions', function(st) {
awsMock.mock('S3', 'getObject', function(){});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('request object createReadStream ignores non-buffer objects', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('call on method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.on, 'function');
st.end();
});
t.test('call send method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.send, 'function');
st.end();
});
t.test('all the methods on a service are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
st.equal(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('only the method on the service is restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('method on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all methods on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> When method is restored, it should be restored on all clients
<DFF> @@ -131,7 +131,6 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message 2');
st.end();
});
-
});
});
t.test('multiple methods can be mocked on the same service', function(st){
| 0 | When method is restored, it should be restored on all clients | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
602 | <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> Avoid stub.restore() in restoreMethod if !stub
This is somewhat like #35 but for a different case. This patch fixes the errors I'm getting in `restore()` when a mocked method is never actually called between being mocked and being restored.
<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 | Avoid stub.restore() in restoreMethod if !stub | 1 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
603 | <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> Avoid stub.restore() in restoreMethod if !stub
This is somewhat like #35 but for a different case. This patch fixes the errors I'm getting in `restore()` when a mocked method is never actually called between being mocked and being restored.
<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 | Avoid stub.restore() in restoreMethod if !stub | 1 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
604 | <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.equals(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.equals(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.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');
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.equals(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.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');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
sns.publish({}, function(err, data){
st.equals(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.equals(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.equals(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.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');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equals(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equals(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.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(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.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');
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.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(data, error);
st.end();
});
});
t.test('promises can be configured', function(st){
awsMock.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.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');
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.equals(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.equals(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const 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'));
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();
}));
});
t.test('request object createReadStream ignores functions', function(st) {
awsMock.mock('S3', 'getObject', function(){});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(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.equals(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.equals(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.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');
});
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');
});
const 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('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.equals(AWS.SNS.isSinonProxy, true);
st.equals(sns1.publish.isSinonProxy, true);
st.equals(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equals(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.equals(AWS.SNS.isSinonProxy, true);
st.equals(sns1.publish.isSinonProxy, true);
st.equals(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equals(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.equals(AWS.SNS.isSinonProxy, true);
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(sns.publish.isSinonProxy, true);
st.equals(docClient.put.isSinonProxy, true);
st.equals(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.put.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equals(data, 'message');
docClient.get({}, function(err, data){
st.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
console.warn(err);
st.equals(data, 'test');
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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
st.equals(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.get.isSinonProxy, true);
st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
st.equals(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equals(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.equals(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equals(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.equals(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} 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.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.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.equals(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.equals(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 #269 from abetomo/upgrade_packages
Upgrade packages
<DFF> @@ -21,7 +21,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -31,7 +31,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -39,12 +39,12 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(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');
+ st.equal(data.test, 'message');
st.end();
});
});
@@ -62,7 +62,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -71,7 +71,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const 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();
});
});
@@ -84,7 +84,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'test');
});
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -97,7 +97,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'test');
});
sns.subscribe({}, function(err, data){
- st.equals(data, 'test');
+ st.equal(data, 'test');
st.end();
});
});
@@ -110,7 +110,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'message 2');
});
sns.subscribe({}, function(err, data){
- st.equals(data, 'message 2');
+ st.equal(data, 'message 2');
st.end();
});
});
@@ -126,10 +126,10 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
sns1.subscribe({}, function(err, data){
- st.equals(data, 'message 2');
+ st.equal(data, 'message 2');
sns2.subscribe({}, function(err, data){
- st.equals(data, 'message 2');
+ st.equal(data, 'message 2');
st.end();
});
});
@@ -143,9 +143,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -161,11 +161,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
- st.equals(data, error);
+ st.equal(data, error);
st.end();
});
});
@@ -179,11 +179,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
- st.equals(data, error);
+ st.equal(data, error);
st.end();
});
});
@@ -209,11 +209,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
- st.equals(data, error);
+ st.equal(data, error);
st.end();
});
});
@@ -232,9 +232,9 @@ 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);
const promise = lambda.getFunction({}).promise();
- st.equals(promise.constructor.name, 'P');
+ st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -262,7 +262,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject', bodyStream);
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -275,7 +275,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -285,7 +285,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -295,7 +295,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -305,7 +305,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '');
+ st.equal(actual.toString(), '');
st.end();
}));
});
@@ -315,7 +315,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '');
+ st.equal(actual.toString(), '');
st.end();
}));
});
@@ -323,25 +323,25 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
- st.equals(typeof req.on, 'function');
+ 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.equals(typeof req.send, 'function');
+ 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.equals(AWS.SNS.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
+ st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('only the method on the service is restored', function(st){
@@ -349,13 +349,13 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'message');
});
const sns = new AWS.SNS();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(sns.publish.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
+ st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
- st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -366,15 +366,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(sns1.publish.isSinonProxy, true);
- st.equals(sns2.publish.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
+ st.equal(sns1.publish.isSinonProxy, true);
+ st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
- st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -385,15 +385,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(sns1.publish.isSinonProxy, true);
- st.equals(sns2.publish.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
+ st.equal(sns1.publish.isSinonProxy, true);
+ st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -410,21 +410,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(sns.publish.isSinonProxy, true);
- st.equals(docClient.put.isSinonProxy, true);
- st.equals(dynamoDb.putItem.isSinonProxy, true);
+ 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.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
- st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
- st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
- st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -437,22 +437,22 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'test');
});
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(docClient.put.isSinonProxy, true);
- st.equals(docClient.get.isSinonProxy, true);
+ 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.equals(data, 'message');
+ st.equal(data, 'message');
docClient.get({}, function(err, data){
- st.equals(data, 'test');
+ st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+ st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
- st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
+ st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
+ st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
@@ -463,11 +463,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(docClient.query.isSinonProxy, true);
+ st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
- console.warn(err);
- st.equals(data, 'test');
+ st.is(err, null);
+ st.equal(data, 'test');
st.end();
});
});
@@ -477,37 +477,37 @@ test('AWS.mock function should mock AWS service and method on the service', func
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(docClient.get.isSinonProxy, true);
- st.equals(dynamoDb.getItem.isSinonProxy, true);
+ 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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.get.isSinonProxy, true);
- st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
+ 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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(docClient.get.isSinonProxy, true);
- st.equals(dynamoDb.getItem.isSinonProxy, true);
+ 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(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
- st.equals(dynamoDb.getItem.isSinonProxy, true);
+ 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.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
- st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
- st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
+ 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();
});
@@ -527,18 +527,18 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
csd.search({}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
- st.equals(data, 'message');
+ 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.equals(stub.stub.isSinonProxy, true);
+ st.equal(stub.stub.isSinonProxy, true);
st.end();
});
@@ -569,7 +569,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
- st.equals(req.on('httpHeaders', ()=>{}), req);
+ st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
@@ -581,7 +581,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
req.send(async (err, data) => {
returnedValue = data.Body;
});
- st.equals(returnedValue, 'body');
+ st.equal(returnedValue, 'body');
st.end();
});
@@ -708,7 +708,7 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -739,7 +739,7 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message2');
+ st.equal(data, 'message2');
st.end();
});
});
| 99 | Merge pull request #269 from abetomo/upgrade_packages | 99 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
605 | <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.equals(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.equals(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.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');
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.equals(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.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');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
sns.publish({}, function(err, data){
st.equals(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.equals(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.equals(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.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');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equals(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equals(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.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(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.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');
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.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(data, error);
st.end();
});
});
t.test('promises can be configured', function(st){
awsMock.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.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');
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.equals(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.equals(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const 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'));
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();
}));
});
t.test('request object createReadStream ignores functions', function(st) {
awsMock.mock('S3', 'getObject', function(){});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(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.equals(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.equals(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.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');
});
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');
});
const 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('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.equals(AWS.SNS.isSinonProxy, true);
st.equals(sns1.publish.isSinonProxy, true);
st.equals(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equals(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.equals(AWS.SNS.isSinonProxy, true);
st.equals(sns1.publish.isSinonProxy, true);
st.equals(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equals(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.equals(AWS.SNS.isSinonProxy, true);
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(sns.publish.isSinonProxy, true);
st.equals(docClient.put.isSinonProxy, true);
st.equals(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.put.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equals(data, 'message');
docClient.get({}, function(err, data){
st.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
console.warn(err);
st.equals(data, 'test');
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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
st.equals(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.get.isSinonProxy, true);
st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.isSinonProxy, true);
st.equals(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equals(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.equals(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equals(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.equals(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} 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.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.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.equals(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.equals(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 #269 from abetomo/upgrade_packages
Upgrade packages
<DFF> @@ -21,7 +21,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -31,7 +31,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -39,12 +39,12 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(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');
+ st.equal(data.test, 'message');
st.end();
});
});
@@ -62,7 +62,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -71,7 +71,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const 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();
});
});
@@ -84,7 +84,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'test');
});
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -97,7 +97,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'test');
});
sns.subscribe({}, function(err, data){
- st.equals(data, 'test');
+ st.equal(data, 'test');
st.end();
});
});
@@ -110,7 +110,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'message 2');
});
sns.subscribe({}, function(err, data){
- st.equals(data, 'message 2');
+ st.equal(data, 'message 2');
st.end();
});
});
@@ -126,10 +126,10 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
sns1.subscribe({}, function(err, data){
- st.equals(data, 'message 2');
+ st.equal(data, 'message 2');
sns2.subscribe({}, function(err, data){
- st.equals(data, 'message 2');
+ st.equal(data, 'message 2');
st.end();
});
});
@@ -143,9 +143,9 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -161,11 +161,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
- st.equals(data, error);
+ st.equal(data, error);
st.end();
});
});
@@ -179,11 +179,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
- st.equals(data, error);
+ st.equal(data, error);
st.end();
});
});
@@ -209,11 +209,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
- st.equals(data, error);
+ st.equal(data, error);
st.end();
});
});
@@ -232,9 +232,9 @@ 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);
const promise = lambda.getFunction({}).promise();
- st.equals(promise.constructor.name, 'P');
+ st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -262,7 +262,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject', bodyStream);
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -275,7 +275,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -285,7 +285,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -295,7 +295,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body');
+ st.equal(actual.toString(), 'body');
st.end();
}));
});
@@ -305,7 +305,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '');
+ st.equal(actual.toString(), '');
st.end();
}));
});
@@ -315,7 +315,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '');
+ st.equal(actual.toString(), '');
st.end();
}));
});
@@ -323,25 +323,25 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
- st.equals(typeof req.on, 'function');
+ 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.equals(typeof req.send, 'function');
+ 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.equals(AWS.SNS.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
+ st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('only the method on the service is restored', function(st){
@@ -349,13 +349,13 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'message');
});
const sns = new AWS.SNS();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(sns.publish.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
+ st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
- st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -366,15 +366,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(sns1.publish.isSinonProxy, true);
- st.equals(sns2.publish.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
+ st.equal(sns1.publish.isSinonProxy, true);
+ st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
- st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -385,15 +385,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(sns1.publish.isSinonProxy, true);
- st.equals(sns2.publish.isSinonProxy, true);
+ st.equal(AWS.SNS.isSinonProxy, true);
+ st.equal(sns1.publish.isSinonProxy, true);
+ st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
- st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -410,21 +410,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
- st.equals(AWS.SNS.isSinonProxy, true);
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(sns.publish.isSinonProxy, true);
- st.equals(docClient.put.isSinonProxy, true);
- st.equals(dynamoDb.putItem.isSinonProxy, true);
+ 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.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
- st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
- st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
- st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
- st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
+ 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){
@@ -437,22 +437,22 @@ test('AWS.mock function should mock AWS service and method on the service', func
callback(null, 'test');
});
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(docClient.put.isSinonProxy, true);
- st.equals(docClient.get.isSinonProxy, true);
+ 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.equals(data, 'message');
+ st.equal(data, 'message');
docClient.get({}, function(err, data){
- st.equals(data, 'test');
+ st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+ st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
- st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
+ st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
+ st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
@@ -463,11 +463,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(docClient.query.isSinonProxy, true);
+ st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
- console.warn(err);
- st.equals(data, 'test');
+ st.is(err, null);
+ st.equal(data, 'test');
st.end();
});
});
@@ -477,37 +477,37 @@ test('AWS.mock function should mock AWS service and method on the service', func
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
- st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(docClient.get.isSinonProxy, true);
- st.equals(dynamoDb.getItem.isSinonProxy, true);
+ 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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.get.isSinonProxy, true);
- st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
+ 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.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(docClient.get.isSinonProxy, true);
- st.equals(dynamoDb.getItem.isSinonProxy, true);
+ 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(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
- st.equals(AWS.DynamoDB.isSinonProxy, true);
- st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
- st.equals(dynamoDb.getItem.isSinonProxy, true);
+ 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.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
- st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
- st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
- st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
+ 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();
});
@@ -527,18 +527,18 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
csd.search({}, function(err, data) {
- st.equals(data, 'message');
+ st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
- st.equals(data, 'message');
+ 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.equals(stub.stub.isSinonProxy, true);
+ st.equal(stub.stub.isSinonProxy, true);
st.end();
});
@@ -569,7 +569,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
- st.equals(req.on('httpHeaders', ()=>{}), req);
+ st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
@@ -581,7 +581,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
req.send(async (err, data) => {
returnedValue = data.Body;
});
- st.equals(returnedValue, 'body');
+ st.equal(returnedValue, 'body');
st.end();
});
@@ -708,7 +708,7 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message');
+ st.equal(data, 'message');
st.end();
});
});
@@ -739,7 +739,7 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
- st.equals(data, 'message2');
+ st.equal(data, 'message2');
st.end();
});
});
| 99 | Merge pull request #269 from abetomo/upgrade_packages | 99 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
606 | <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();
}));
});
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();
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 #166 from abetomo/use_buffer_alloc
Fix to use 'Buffer.alloc' instead of 'new Buffer'
<DFF> @@ -254,7 +254,7 @@ 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', new Buffer('body'));
+ awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
var s3 = new AWS.S3();
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
| 1 | Merge pull request #166 from abetomo/use_buffer_alloc | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
607 | <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();
}));
});
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();
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 #166 from abetomo/use_buffer_alloc
Fix to use 'Buffer.alloc' instead of 'new Buffer'
<DFF> @@ -254,7 +254,7 @@ 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', new Buffer('body'));
+ awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
var s3 = new AWS.S3();
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
| 1 | Merge pull request #166 from abetomo/use_buffer_alloc | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
608 | <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> Adds test for setSDK() method
<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 | Adds test for setSDK() method | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
609 | <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> Adds test for setSDK() method
<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 | Adds test for setSDK() method | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
610 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- "4.2.3"
- "node"
before_install:
- pip install --user codecov
after_success:
<MSG> Merge pull request #131 from kevinrambaud/update-travis-node-versions
Add testing on more node versions
<DFF> @@ -1,7 +1,9 @@
language: node_js
node_js:
- - "4.2.3"
- - "node"
+ - "4"
+ - "6"
+ - "8"
+ - "10"
before_install:
- pip install --user codecov
after_success:
| 4 | Merge pull request #131 from kevinrambaud/update-travis-node-versions | 2 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
611 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- "4.2.3"
- "node"
before_install:
- pip install --user codecov
after_success:
<MSG> Merge pull request #131 from kevinrambaud/update-travis-node-versions
Add testing on more node versions
<DFF> @@ -1,7 +1,9 @@
language: node_js
node_js:
- - "4.2.3"
- - "node"
+ - "4"
+ - "6"
+ - "8"
+ - "10"
before_install:
- pip install --user codecov
after_success:
| 4 | Merge pull request #131 from kevinrambaud/update-travis-node-versions | 2 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
612 | <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
**/
var sinon = require('sinon');
var traverse = require('traverse');
var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
var AWS = {};
var 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) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
const client = new services[service].Constructor(...args);
services[service].clients = services[service].clients || [];
services[service].clients.push(client);
// Once this has been triggered we can mock out all the registered methods.
for (const key in services[service].methodMocks) {
mockServiceMethod(service, client, key, services[service].methodMocks[key].replace);
};
return client;
});
services[service].stub = serviceStub;
};
/**
* Wraps a sinon stub or jest mock function as a fully functional replacement function
*/
function wrapTestStubReplaceFn(replace) {
if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) {
return replace;
}
return (params, cb) => {
// If only one argument is provided, it is the callback
if (!cb) {
cb = params;
params = {};
}
// Spy on the users callback so we can later on determine if it has been called in their replace
const cbSpy = sinon.spy(cb);
try {
// Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters
const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy);
// If the users replace already called the callback, there's no more need for us do it.
if (cbSpy.called) {
return;
}
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
cb(undefined, result);
}
} catch (err) {
cb(err);
}
};
}
/**
* Stubs the method on a service.
*
* All AWS service methods take two argument:
* - params: an object.
* - callback: of the form 'function(err, data) {}'.
*/
function mockServiceMethod(service, client, method, replace) {
replace = wrapTestStubReplaceFn(replace);
services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() {
const args = Array.prototype.slice.call(arguments);
let userArgs, userCallback;
if (typeof args[(args.length || 1) - 1] === 'function') {
userArgs = args.slice(0, -1);
userCallback = args[(args.length || 1) - 1];
} else {
userArgs = args;
}
const havePromises = typeof AWS.Promise === 'function';
let promise, resolve, reject, storedResult;
const tryResolveFromStored = function() {
if (storedResult && promise) {
if (typeof storedResult.then === 'function') {
storedResult.then(resolve, reject)
} else if (storedResult.reject) {
reject(storedResult.reject);
} else {
resolve(storedResult.resolve);
}
}
};
const callback = function(err, data) {
if (!storedResult) {
if (err) {
storedResult = {reject: err};
} else {
storedResult = {resolve: data};
}
}
if (userCallback) {
userCallback(err, data);
}
tryResolveFromStored();
};
const request = {
promise: havePromises ? function() {
if (!promise) {
promise = new AWS.Promise(function (resolve_, reject_) {
resolve = resolve_;
reject = reject_;
});
}
tryResolveFromStored();
return promise;
} : undefined,
createReadStream: function() {
if (storedResult instanceof Readable) {
return storedResult;
}
if (replace instanceof Readable) {
return replace;
} else {
const stream = new Readable();
stream._read = function(size) {
if (typeof replace === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
};
return stream;
}
},
on: function(eventName, callback) {
return this;
},
send: function(callback) {
callback(storedResult.reject, storedResult.resolve);
}
};
// different locations for the paramValidation property
const config = (client.config || client.options || _AWS.config);
if (config.paramValidation) {
try {
// different strategies to find method, depending on wether the service is nested/unnested
const inputRules =
((client.api && client.api.operations[method]) || client[method] || {}).input;
if (inputRules) {
const params = userArgs[(userArgs.length || 1) - 1];
new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params);
}
} catch (e) {
callback(e, null);
return request;
}
}
// If the value of 'replace' is a function we call it with the arguments.
if (typeof replace === 'function') {
const result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
(typeof result.then === 'function' || result instanceof Readable)) {
storedResult = result
}
}
// Else we call the callback with the value of 'replace'.
else {
callback(null, replace);
}
return request;
});
}
/**
* Restores the mocks for just one method on a service, the entire service, or all mocks.
*
* When no parameters are passed, everything will be reset.
* When only the service is passed, that specific service will be reset.
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
if (!service) {
restoreAllServices();
} else {
if (method) {
restoreMethod(service, method);
} else {
restoreService(service);
}
};
};
/**
* Restores all mocked service and their corresponding methods.
*/
function restoreAllServices() {
for (const service in services) {
restoreService(service);
}
}
/**
* Restores a single mocked service and its corresponding methods.
*/
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
}
}
/**
* Restores all mocked methods on a service.
*/
function restoreAllMethods(service) {
for (const method in services[service].methodMocks) {
restoreMethod(service, method);
}
}
/**
* Restores a single mocked method on a service.
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
if (services[service].methodMocks[method].stub) {
// restore this method on all clients
services[service].clients.forEach(client => {
if (client[method] && typeof client[method].restore === 'function') {
client[method].restore();
}
})
}
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
}
}
(function() {
const setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
if (typeof setPromisesDependency === 'function') {
AWS.Promise = global.Promise;
_AWS.config.setPromisesDependency = function(p) {
AWS.Promise = p;
return setPromisesDependency(p);
};
}
})();
module.exports = AWS;
<MSG> Merge pull request #167 from abetomo/add_no-multi-spaces_rule
Add `no-multi-spaces` rule
<DFF> @@ -12,10 +12,10 @@
var sinon = require('sinon');
var traverse = require('traverse');
-var _AWS = require('aws-sdk');
+var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
-var AWS = {};
+var AWS = {};
var services = {};
/**
@@ -35,7 +35,7 @@ AWS.setSDKInstance = function(sdk) {
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] = {};
+ services[service] = {};
/**
* Save the real constructor so we can invoke it later on.
@@ -96,7 +96,7 @@ function mockService(service) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
- var client = new services[service].Constructor(args);
+ var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
| 4 | Merge pull request #167 from abetomo/add_no-multi-spaces_rule | 4 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
613 | <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
**/
var sinon = require('sinon');
var traverse = require('traverse');
var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
var AWS = {};
var 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) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
const client = new services[service].Constructor(...args);
services[service].clients = services[service].clients || [];
services[service].clients.push(client);
// Once this has been triggered we can mock out all the registered methods.
for (const key in services[service].methodMocks) {
mockServiceMethod(service, client, key, services[service].methodMocks[key].replace);
};
return client;
});
services[service].stub = serviceStub;
};
/**
* Wraps a sinon stub or jest mock function as a fully functional replacement function
*/
function wrapTestStubReplaceFn(replace) {
if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) {
return replace;
}
return (params, cb) => {
// If only one argument is provided, it is the callback
if (!cb) {
cb = params;
params = {};
}
// Spy on the users callback so we can later on determine if it has been called in their replace
const cbSpy = sinon.spy(cb);
try {
// Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters
const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy);
// If the users replace already called the callback, there's no more need for us do it.
if (cbSpy.called) {
return;
}
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
cb(undefined, result);
}
} catch (err) {
cb(err);
}
};
}
/**
* Stubs the method on a service.
*
* All AWS service methods take two argument:
* - params: an object.
* - callback: of the form 'function(err, data) {}'.
*/
function mockServiceMethod(service, client, method, replace) {
replace = wrapTestStubReplaceFn(replace);
services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() {
const args = Array.prototype.slice.call(arguments);
let userArgs, userCallback;
if (typeof args[(args.length || 1) - 1] === 'function') {
userArgs = args.slice(0, -1);
userCallback = args[(args.length || 1) - 1];
} else {
userArgs = args;
}
const havePromises = typeof AWS.Promise === 'function';
let promise, resolve, reject, storedResult;
const tryResolveFromStored = function() {
if (storedResult && promise) {
if (typeof storedResult.then === 'function') {
storedResult.then(resolve, reject)
} else if (storedResult.reject) {
reject(storedResult.reject);
} else {
resolve(storedResult.resolve);
}
}
};
const callback = function(err, data) {
if (!storedResult) {
if (err) {
storedResult = {reject: err};
} else {
storedResult = {resolve: data};
}
}
if (userCallback) {
userCallback(err, data);
}
tryResolveFromStored();
};
const request = {
promise: havePromises ? function() {
if (!promise) {
promise = new AWS.Promise(function (resolve_, reject_) {
resolve = resolve_;
reject = reject_;
});
}
tryResolveFromStored();
return promise;
} : undefined,
createReadStream: function() {
if (storedResult instanceof Readable) {
return storedResult;
}
if (replace instanceof Readable) {
return replace;
} else {
const stream = new Readable();
stream._read = function(size) {
if (typeof replace === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
};
return stream;
}
},
on: function(eventName, callback) {
return this;
},
send: function(callback) {
callback(storedResult.reject, storedResult.resolve);
}
};
// different locations for the paramValidation property
const config = (client.config || client.options || _AWS.config);
if (config.paramValidation) {
try {
// different strategies to find method, depending on wether the service is nested/unnested
const inputRules =
((client.api && client.api.operations[method]) || client[method] || {}).input;
if (inputRules) {
const params = userArgs[(userArgs.length || 1) - 1];
new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params);
}
} catch (e) {
callback(e, null);
return request;
}
}
// If the value of 'replace' is a function we call it with the arguments.
if (typeof replace === 'function') {
const result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
(typeof result.then === 'function' || result instanceof Readable)) {
storedResult = result
}
}
// Else we call the callback with the value of 'replace'.
else {
callback(null, replace);
}
return request;
});
}
/**
* Restores the mocks for just one method on a service, the entire service, or all mocks.
*
* When no parameters are passed, everything will be reset.
* When only the service is passed, that specific service will be reset.
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
if (!service) {
restoreAllServices();
} else {
if (method) {
restoreMethod(service, method);
} else {
restoreService(service);
}
};
};
/**
* Restores all mocked service and their corresponding methods.
*/
function restoreAllServices() {
for (const service in services) {
restoreService(service);
}
}
/**
* Restores a single mocked service and its corresponding methods.
*/
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
}
}
/**
* Restores all mocked methods on a service.
*/
function restoreAllMethods(service) {
for (const method in services[service].methodMocks) {
restoreMethod(service, method);
}
}
/**
* Restores a single mocked method on a service.
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
if (services[service].methodMocks[method].stub) {
// restore this method on all clients
services[service].clients.forEach(client => {
if (client[method] && typeof client[method].restore === 'function') {
client[method].restore();
}
})
}
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
}
}
(function() {
const setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
if (typeof setPromisesDependency === 'function') {
AWS.Promise = global.Promise;
_AWS.config.setPromisesDependency = function(p) {
AWS.Promise = p;
return setPromisesDependency(p);
};
}
})();
module.exports = AWS;
<MSG> Merge pull request #167 from abetomo/add_no-multi-spaces_rule
Add `no-multi-spaces` rule
<DFF> @@ -12,10 +12,10 @@
var sinon = require('sinon');
var traverse = require('traverse');
-var _AWS = require('aws-sdk');
+var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
-var AWS = {};
+var AWS = {};
var services = {};
/**
@@ -35,7 +35,7 @@ AWS.setSDKInstance = function(sdk) {
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] = {};
+ services[service] = {};
/**
* Save the real constructor so we can invoke it later on.
@@ -96,7 +96,7 @@ function mockService(service) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
- var client = new services[service].Constructor(args);
+ var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
| 4 | Merge pull request #167 from abetomo/add_no-multi-spaces_rule | 4 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
614 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
const test = tap.test;
const awsMock = require('../index.js');
const AWS = require('aws-sdk');
const isNodeStream = require('is-node-stream');
const concatStream = require('concat-stream');
const Readable = require('stream').Readable;
const jest = require('jest-mock');
const sinon = require('sinon');
AWS.config.paramValidation = false;
tap.afterEach(() => {
awsMock.restore();
});
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('mock function replaces method with a function that returns replace string', function(st){
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
callback(null, options);
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equal(data.test, 'message');
st.end();
});
});
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
st.end();
});
});
t.test('method with no input rules can be mocked even if paramValidation is set', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
t.test('method succeeds on valid input when paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equal(data.Body, 'body');
st.end();
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'test');
});
sns.subscribe({}, function(err, data){
st.equal(data, 'test');
st.end();
});
});
t.test('service is re-mocked when remock called', function(st){
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
const sns = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
sns.subscribe({}, function(err, data){
st.equal(data, 'message 2');
st.end();
});
});
t.test('all instances of service are re-mocked when remock called', function(st){
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
sns1.subscribe({}, function(err, data){
st.equal(data, 'message 2');
sns2.subscribe({}, function(err, data){
st.equal(data, 'message 2');
st.end();
});
});
});
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
});
if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(error, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('replacement returns thennable', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params) {
return Promise.resolve('message')
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
return Promise.reject(error)
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('no unhandled promise rejections when promises are not used', function(st) {
process.on('unhandledRejection', function(reason, promise) {
st.fail('unhandledRejection, reason follows');
st.error(reason);
});
awsMock.mock('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
const S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
setTimeout(callback.bind(this, error, 'message'), 10);
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('promises can be configured', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
function P(handler) {
const self = this;
function yay (value) {
self.value = value;
}
handler(yay, function(){});
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
st.equal(data, 'message');
st.end();
});
});
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
let req = s3.getObject('getObject', function(err, data) {});
st.ok(isNodeStream(req.createReadStream()));
// with or without callback
req = s3.getObject('getObject');
st.ok(isNodeStream(req.createReadStream()));
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with returned streams', function(st) {
awsMock.mock('S3', 'getObject', () => {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
return bodyStream;
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream ignores functions', function(st) {
awsMock.mock('S3', 'getObject', function(){});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('request object createReadStream ignores non-buffer objects', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('call on method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.on, 'function');
st.end();
});
t.test('call send method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.send, 'function');
st.end();
});
t.test('all the methods on a service are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
st.equal(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('only the method on the service is restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('method on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all methods on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn().mockImplementation(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.end();
});
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 #257 from thomaux/fix-256
Fixes #256
<DFF> @@ -620,6 +620,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
+ t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
+ const jestMock = jest.fn().mockReturnValue('message');
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem(function(err, data){
+ st.equal(data, 'message');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
@@ -632,7 +643,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
- const jestMock = jest.fn().mockImplementation(() => {
+ const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
@@ -655,6 +666,39 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
+ t.test('mock function replaces method with a jest mock with implementation', function(st) {
+ const jestMock = jest.fn((params, cb) => cb(null, 'item'));
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(jestMock.mock.calls.length, 1);
+ st.equal(data, 'item');
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
+ const jestMock = jest.fn((params, cb) => cb(null, 'item'));
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem(function(err, data){
+ st.equal(jestMock.mock.calls.length, 1);
+ st.equal(data, 'item');
+ st.end();
+ });
+ });
+
+ t.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();
});
| 45 | Merge pull request #257 from thomaux/fix-256 | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
615 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
const test = tap.test;
const awsMock = require('../index.js');
const AWS = require('aws-sdk');
const isNodeStream = require('is-node-stream');
const concatStream = require('concat-stream');
const Readable = require('stream').Readable;
const jest = require('jest-mock');
const sinon = require('sinon');
AWS.config.paramValidation = false;
tap.afterEach(() => {
awsMock.restore();
});
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('mock function replaces method with a function that returns replace string', function(st){
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
callback(null, options);
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equal(data.test, 'message');
st.end();
});
});
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
st.end();
});
});
t.test('method with no input rules can be mocked even if paramValidation is set', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
t.test('method succeeds on valid input when paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equal(data.Body, 'body');
st.end();
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'test');
});
sns.subscribe({}, function(err, data){
st.equal(data, 'test');
st.end();
});
});
t.test('service is re-mocked when remock called', function(st){
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
const sns = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
sns.subscribe({}, function(err, data){
st.equal(data, 'message 2');
st.end();
});
});
t.test('all instances of service are re-mocked when remock called', function(st){
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
sns1.subscribe({}, function(err, data){
st.equal(data, 'message 2');
sns2.subscribe({}, function(err, data){
st.equal(data, 'message 2');
st.end();
});
});
});
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}, function(err, data) {
st.equal(data, 'message');
lambda.createFunction({}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
});
if (typeof Promise === 'function') {
t.test('promises are supported', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
callback(error, 'message');
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('replacement returns thennable', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params) {
return Promise.resolve('message')
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
return Promise.reject(error)
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('no unhandled promise rejections when promises are not used', function(st) {
process.on('unhandledRejection', function(reason, promise) {
st.fail('unhandledRejection, reason follows');
st.error(reason);
});
awsMock.mock('S3', 'getObject', function(params, callback) {
callback('This is a test error to see if promise rejections go unhandled');
});
const S3 = new AWS.S3();
S3.getObject({}, function(err, data) {});
st.end();
});
t.test('promises work with async completion', function(st){
const error = new Error('on purpose');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
setTimeout(callback.bind(this, null, 'message'), 10);
});
awsMock.mock('Lambda', 'createFunction', function(params, callback) {
setTimeout(callback.bind(this, error, 'message'), 10);
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise();
}).catch(function(data){
st.equal(data, error);
st.end();
});
});
t.test('promises can be configured', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
const lambda = new AWS.Lambda();
function P(handler) {
const self = this;
function yay (value) {
self.value = value;
}
handler(yay, function(){});
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
st.equal(promise.constructor.name, 'P');
promise.then(function(data) {
st.equal(data, 'message');
st.end();
});
});
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
let req = s3.getObject('getObject', function(err, data) {});
st.ok(isNodeStream(req.createReadStream()));
// with or without callback
req = s3.getObject('getObject');
st.ok(isNodeStream(req.createReadStream()));
// stream is currently always empty but that's subject to change.
// let's just consume it and ignore the contents
req = s3.getObject('getObject');
const stream = req.createReadStream();
stream.pipe(concatStream(function() {
st.end();
}));
});
t.test('request object createReadStream works with streams', function(st) {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
awsMock.mock('S3', 'getObject', bodyStream);
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with returned streams', function(st) {
awsMock.mock('S3', 'getObject', () => {
const bodyStream = new Readable();
bodyStream.push('body');
bodyStream.push(null);
return bodyStream;
});
const stream = new AWS.S3().getObject('getObject').createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream works with buffers', function(st) {
awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), 'body');
st.end();
}));
});
t.test('request object createReadStream ignores functions', function(st) {
awsMock.mock('S3', 'getObject', function(){});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('request object createReadStream ignores non-buffer objects', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
const stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equal(actual.toString(), '');
st.end();
}));
});
t.test('call on method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.on, 'function');
st.end();
});
t.test('call send method of request object', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
st.equal(typeof req.send, 'function');
st.end();
});
t.test('all the methods on a service are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
st.equal(AWS.SNS.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('only the method on the service is restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('method on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all methods on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn().mockImplementation(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.end();
});
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 #257 from thomaux/fix-256
Fixes #256
<DFF> @@ -620,6 +620,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
+ t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
+ const jestMock = jest.fn().mockReturnValue('message');
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem(function(err, data){
+ st.equal(data, 'message');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
@@ -632,7 +643,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
- const jestMock = jest.fn().mockImplementation(() => {
+ const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
@@ -655,6 +666,39 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
});
+ t.test('mock function replaces method with a jest mock with implementation', function(st) {
+ const jestMock = jest.fn((params, cb) => cb(null, 'item'));
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(jestMock.mock.calls.length, 1);
+ st.equal(data, 'item');
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
+ const jestMock = jest.fn((params, cb) => cb(null, 'item'));
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem(function(err, data){
+ st.equal(jestMock.mock.calls.length, 1);
+ st.equal(data, 'item');
+ st.end();
+ });
+ });
+
+ t.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();
});
| 45 | Merge pull request #257 from thomaux/fix-256 | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
616 | <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> Add parserOptions to .eslintrc.json
I get the following error.
```
/path/aws-sdk-mock/index.js
91:67 error Parsing error: Unexpected token .
```
<DFF> @@ -7,6 +7,9 @@
"Buffer": true,
"escape": true
},
+ "parserOptions": {
+ "ecmaVersion": 2017
+ },
"rules": {
"quotes": [2, "single"],
"strict": 0,
| 3 | Add parserOptions to .eslintrc.json | 0 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
617 | <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> Add parserOptions to .eslintrc.json
I get the following error.
```
/path/aws-sdk-mock/index.js
91:67 error Parsing error: Unexpected token .
```
<DFF> @@ -7,6 +7,9 @@
"Buffer": true,
"escape": true
},
+ "parserOptions": {
+ "ecmaVersion": 2017
+ },
"rules": {
"quotes": [2, "single"],
"strict": 0,
| 3 | Add parserOptions to .eslintrc.json | 0 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
618 | <NME> index.test-d.ts
<BEF> import * as AWS from 'aws-sdk';
import { AWSError } from 'aws-sdk';
import { ListObjectsV2Request } from 'aws-sdk/clients/s3';
import { expectError, expectType } from 'tsd';
import { mock, remock, restore, setSDK, setSDKInstance } from '../index';
const awsError: AWSError = {
name: 'AWSError',
message: 'message',
code: 'code',
time: new Date(),
};
/**
* mock
*/
expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => {
expectType<ListObjectsV2Request>(params);
const output: AWS.S3.ListObjectsV2Output = {
Name: params.Bucket,
MaxKeys: params.MaxKeys,
Delimiter: params.Delimiter,
Prefix: params.Prefix,
KeyCount: 1,
IsTruncated: false,
ContinuationToken: params.ContinuationToken,
Contents: [
{
LastModified: new Date(),
ETag: '"668d791b0c7d6a7f0f86c269888b4546"',
StorageClass: 'STANDARD',
Key: 'aws-sdk-mock/index.js',
Size: 8524,
},
]
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectType<void>(remock('EC2', 'stopInstances', (params, callback) => {
// $ExpectType string[]
const instanceIds = params.InstanceIds;
expectType<string[]>(instanceIds);
const output: AWS.EC2.StopInstancesResult = {
StoppingInstances: instanceIds.map(id => ({
InstanceId: id,
PreviousState: { Name: 'running' },
CurrentState: { Name: 'stopping' },
})),
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
/**
* Remock
*/
expectType<void>(remock('Snowball', 'makeRequest', undefined));
expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined));
expectError(remock('Snowball', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentServer', 'get', undefined));
/**
* Restore
*/
expectType<void>(restore('Pricing', 'getProducts'));
expectType<void>(restore('DynamoDB.DocumentClient', 'get'));
expectError(restore('Pricing', 'borrowMoney'));
expectError(restore('DynamoDB.DocumentClient', 'unknown'));
expectType<void>(restore('KMS'));
expectType<void>(restore('DynamoDB.DocumentClient'));
expectError(restore('Skynet'));
expectError(restore('DynamoDB.DocumentServer'));
expectError(restore(42));
expectType<void>(restore());
expectError(restore(null));
/**
* setSDK
*/
expectType<void>(setSDK('aws-sdk'));
/**
* setSDKInstance
*/
expectType<void>(setSDKInstance(AWS));
expectError(setSDKInstance(import('aws-sdk')));
async function foo() {
expectType<void>(setSDKInstance(await import('aws-sdk')));
}
expectError(setSDKInstance(AWS.S3));
import allClients = require('aws-sdk/clients/all');
expectError(setSDKInstance(allClients));
<MSG> Merge pull request #260 from thomaux/fix-259
#259: patch nested client names
<DFF> @@ -51,6 +51,10 @@ expectError(mock('S3', 'describeObjects', (params, callback) => {
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
+expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen'));
+
+expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen'));
+expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
| 4 | Merge pull request #260 from thomaux/fix-259 | 0 | .ts | test-d | apache-2.0 | dwyl/aws-sdk-mock |
619 | <NME> index.test-d.ts
<BEF> import * as AWS from 'aws-sdk';
import { AWSError } from 'aws-sdk';
import { ListObjectsV2Request } from 'aws-sdk/clients/s3';
import { expectError, expectType } from 'tsd';
import { mock, remock, restore, setSDK, setSDKInstance } from '../index';
const awsError: AWSError = {
name: 'AWSError',
message: 'message',
code: 'code',
time: new Date(),
};
/**
* mock
*/
expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => {
expectType<ListObjectsV2Request>(params);
const output: AWS.S3.ListObjectsV2Output = {
Name: params.Bucket,
MaxKeys: params.MaxKeys,
Delimiter: params.Delimiter,
Prefix: params.Prefix,
KeyCount: 1,
IsTruncated: false,
ContinuationToken: params.ContinuationToken,
Contents: [
{
LastModified: new Date(),
ETag: '"668d791b0c7d6a7f0f86c269888b4546"',
StorageClass: 'STANDARD',
Key: 'aws-sdk-mock/index.js',
Size: 8524,
},
]
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectType<void>(remock('EC2', 'stopInstances', (params, callback) => {
// $ExpectType string[]
const instanceIds = params.InstanceIds;
expectType<string[]>(instanceIds);
const output: AWS.EC2.StopInstancesResult = {
StoppingInstances: instanceIds.map(id => ({
InstanceId: id,
PreviousState: { Name: 'running' },
CurrentState: { Name: 'stopping' },
})),
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
/**
* Remock
*/
expectType<void>(remock('Snowball', 'makeRequest', undefined));
expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined));
expectError(remock('Snowball', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentServer', 'get', undefined));
/**
* Restore
*/
expectType<void>(restore('Pricing', 'getProducts'));
expectType<void>(restore('DynamoDB.DocumentClient', 'get'));
expectError(restore('Pricing', 'borrowMoney'));
expectError(restore('DynamoDB.DocumentClient', 'unknown'));
expectType<void>(restore('KMS'));
expectType<void>(restore('DynamoDB.DocumentClient'));
expectError(restore('Skynet'));
expectError(restore('DynamoDB.DocumentServer'));
expectError(restore(42));
expectType<void>(restore());
expectError(restore(null));
/**
* setSDK
*/
expectType<void>(setSDK('aws-sdk'));
/**
* setSDKInstance
*/
expectType<void>(setSDKInstance(AWS));
expectError(setSDKInstance(import('aws-sdk')));
async function foo() {
expectType<void>(setSDKInstance(await import('aws-sdk')));
}
expectError(setSDKInstance(AWS.S3));
import allClients = require('aws-sdk/clients/all');
expectError(setSDKInstance(allClients));
<MSG> Merge pull request #260 from thomaux/fix-259
#259: patch nested client names
<DFF> @@ -51,6 +51,10 @@ expectError(mock('S3', 'describeObjects', (params, callback) => {
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
+expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen'));
+
+expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen'));
+expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
| 4 | Merge pull request #260 from thomaux/fix-259 | 0 | .ts | test-d | apache-2.0 | dwyl/aws-sdk-mock |
620 | <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.mock('SNS', 'publish', 'message')
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
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: setSDKInstance to allow mocking of specific aws objects
<DFF> @@ -373,7 +373,36 @@ 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();
+});
+
+test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
+ t.test('Specific Modules can be set for mocking', function(st) {
+ var aws2 = require('aws-sdk')
+ awsMock.setSDKInstance(aws2);
+ awsMock.mock('SNS', 'publish', 'message2');
+ var sns = new AWS.SNS();
+ sns.publish({}, function(err, data){
+ st.equals(data, 'message2');
+ awsMock.restore('SNS');
+ st.end();
+ })
+ });
+
+ t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
+ var bad = {}
+ awsMock.setSDKInstance(bad);
+ st.throws(function() {
+ awsMock.mock('SNS', 'publish', 'message')
+ });
+ awsMock.setSDKInstance(AWS);
+ awsMock.restore()
st.end();
});
t.end();
});
+
| 29 | feat: setSDKInstance to allow mocking of specific aws objects | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
621 | <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.mock('SNS', 'publish', 'message')
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
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: setSDKInstance to allow mocking of specific aws objects
<DFF> @@ -373,7 +373,36 @@ 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();
+});
+
+test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
+ t.test('Specific Modules can be set for mocking', function(st) {
+ var aws2 = require('aws-sdk')
+ awsMock.setSDKInstance(aws2);
+ awsMock.mock('SNS', 'publish', 'message2');
+ var sns = new AWS.SNS();
+ sns.publish({}, function(err, data){
+ st.equals(data, 'message2');
+ awsMock.restore('SNS');
+ st.end();
+ })
+ });
+
+ t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
+ var bad = {}
+ awsMock.setSDKInstance(bad);
+ st.throws(function() {
+ awsMock.mock('SNS', 'publish', 'message')
+ });
+ awsMock.setSDKInstance(AWS);
+ awsMock.restore()
st.end();
});
t.end();
});
+
| 29 | feat: setSDKInstance to allow mocking of specific aws objects | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
622 | <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;
var AWS = {};
var services = {};
/**
* Stubs the service and registers the method that needs to be mocked.
*/
};
/**
* 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> Adds method to change aws-sdk to be mocked
<DFF> @@ -17,6 +17,13 @@ var _AWS = require('aws-sdk');
var AWS = {};
var services = {};
+/**
+ * Sets the aws-sdk to be mocked.
+ */
+AWS.setSDK = function(path) {
+ _AWS = require(path);
+};
+
/**
* Stubs the service and registers the method that needs to be mocked.
*/
| 7 | Adds method to change aws-sdk to be mocked | 0 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
623 | <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;
var AWS = {};
var services = {};
/**
* Stubs the service and registers the method that needs to be mocked.
*/
};
/**
* 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> Adds method to change aws-sdk to be mocked
<DFF> @@ -17,6 +17,13 @@ var _AWS = require('aws-sdk');
var AWS = {};
var services = {};
+/**
+ * Sets the aws-sdk to be mocked.
+ */
+AWS.setSDK = function(path) {
+ _AWS = require(path);
+};
+
/**
* Stubs the service and registers the method that needs to be mocked.
*/
| 7 | Adds method to change aws-sdk to be mocked | 0 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
624 | <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> 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 | Refactored code to use config parameters from the real constructor | 8 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
625 | <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> 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 | Refactored code to use config parameters from the real constructor | 8 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
626 | <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
**/
var sinon = require('sinon');
var traverse = require('traverse');
var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
var AWS = {};
var 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) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
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> Add no-multi-spaces rule
<DFF> @@ -12,10 +12,10 @@
var sinon = require('sinon');
var traverse = require('traverse');
-var _AWS = require('aws-sdk');
+var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
-var AWS = {};
+var AWS = {};
var services = {};
/**
@@ -35,7 +35,7 @@ AWS.setSDKInstance = function(sdk) {
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] = {};
+ services[service] = {};
/**
* Save the real constructor so we can invoke it later on.
@@ -96,7 +96,7 @@ function mockService(service) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
- var client = new services[service].Constructor(args);
+ var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
| 4 | Add no-multi-spaces rule | 4 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
627 | <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
**/
var sinon = require('sinon');
var traverse = require('traverse');
var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
var AWS = {};
var 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) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
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> Add no-multi-spaces rule
<DFF> @@ -12,10 +12,10 @@
var sinon = require('sinon');
var traverse = require('traverse');
-var _AWS = require('aws-sdk');
+var _AWS = require('aws-sdk');
var Readable = require('stream').Readable;
-var AWS = {};
+var AWS = {};
var services = {};
/**
@@ -35,7 +35,7 @@ AWS.setSDKInstance = function(sdk) {
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] = {};
+ services[service] = {};
/**
* Save the real constructor so we can invoke it later on.
@@ -96,7 +96,7 @@ function mockService(service) {
* we stored before. E.g. var client = new AWS.SNS()
* This is necessary in order to mock methods on the service.
*/
- var client = new services[service].Constructor(args);
+ var client = new services[service].Constructor(args);
services[service].client = client;
// Once this has been triggered we can mock out all the registered methods.
| 4 | Add no-multi-spaces rule | 4 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
628 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- "node"
- "6"
- "8"
- "10"
- "12"
<MSG> Remove Node.js6 from travis.yml
* Node.js6 is EOL.
* https://github.com/nodejs/Release
* Because tap does not support Node.js 6 or less.
* https://github.com/tapjs/node-tap/blob/master/package.json#L11-L13
<DFF> @@ -1,7 +1,6 @@
language: node_js
node_js:
- "node"
- - "6"
- "8"
- "10"
- "12"
| 0 | Remove Node.js6 from travis.yml | 1 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
629 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- "node"
- "6"
- "8"
- "10"
- "12"
<MSG> Remove Node.js6 from travis.yml
* Node.js6 is EOL.
* https://github.com/nodejs/Release
* Because tap does not support Node.js 6 or less.
* https://github.com/tapjs/node-tap/blob/master/package.json#L11-L13
<DFF> @@ -1,7 +1,6 @@
language: node_js
node_js:
- "node"
- - "6"
- "8"
- "10"
- "12"
| 0 | Remove Node.js6 from travis.yml | 1 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
630 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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();
});
}
```
### Don't worry about the constructor configuration
Some constructors of the aws-sdk will require you to pass through a configuration object.
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> Added documentation for this feature in README.md
<DFF> @@ -86,6 +86,34 @@ exports.handler = function(event, context) {
}
```
+### 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:
+
+```
+AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
+ callback(null, {Item: {Key: 'Value'}});
+});
+```
+
+**NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent:
+
+```
+// OK
+AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
+AWS.mock('DynamoDB', 'describeTable', 'message');
+AWS.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.
| 28 | Added documentation for this feature in README.md | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
631 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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();
});
}
```
### Don't worry about the constructor configuration
Some constructors of the aws-sdk will require you to pass through a configuration object.
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> Added documentation for this feature in README.md
<DFF> @@ -86,6 +86,34 @@ exports.handler = function(event, context) {
}
```
+### 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:
+
+```
+AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
+ callback(null, {Item: {Key: 'Value'}});
+});
+```
+
+**NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent:
+
+```
+// OK
+AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
+AWS.mock('DynamoDB', 'describeTable', 'message');
+AWS.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.
| 28 | Added documentation for this feature in README.md | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
632 | <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();
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
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 #236 from moish83/return-stream
issue#97 - Stream depending on params for S3.getObject
<DFF> @@ -245,6 +245,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('request object createReadStream works with returned streams', function(st) {
+ awsMock.mock('S3', 'getObject', () => {
+ const bodyStream = new Readable();
+ bodyStream.push('body');
+ bodyStream.push(null);
+ return bodyStream;
+ });
+ const stream = new AWS.S3().getObject('getObject').createReadStream();
+ stream.pipe(concatStream(function(actual) {
+ st.equals(actual.toString(), 'body');
+ st.end();
+ }));
+ });
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
| 13 | Merge pull request #236 from moish83/return-stream | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
633 | <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();
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
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 #236 from moish83/return-stream
issue#97 - Stream depending on params for S3.getObject
<DFF> @@ -245,6 +245,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('request object createReadStream works with returned streams', function(st) {
+ awsMock.mock('S3', 'getObject', () => {
+ const bodyStream = new Readable();
+ bodyStream.push('body');
+ bodyStream.push(null);
+ return bodyStream;
+ });
+ const stream = new AWS.S3().getObject('getObject').createReadStream();
+ stream.pipe(concatStream(function(actual) {
+ st.equals(actual.toString(), 'body');
+ st.end();
+ }));
+ });
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
| 13 | Merge pull request #236 from moish83/return-stream | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
634 | <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> Merge pull request #19 from mkjois/master
Small change allowing the replace function to accept any number of arguments
<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 | Merge pull request #19 from mkjois/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
635 | <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> Merge pull request #19 from mkjois/master
Small change allowing the replace function to accept any number of arguments
<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 | Merge pull request #19 from mkjois/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
636 | <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> 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 | Fix request.send not resolving | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
637 | <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> 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 | Fix request.send not resolving | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
638 | <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 }]
}
}
"space-unary-ops": [1, { "words": true, "nonwords": false }]
}
}
<MSG> Fix .eslintrc.json indent
<DFF> @@ -1,24 +1,24 @@
{
"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
+ },
+ "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 }]
+ }
}
| 19 | Fix .eslintrc.json indent | 19 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
639 | <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 }]
}
}
"space-unary-ops": [1, { "words": true, "nonwords": false }]
}
}
<MSG> Fix .eslintrc.json indent
<DFF> @@ -1,24 +1,24 @@
{
"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
+ },
+ "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 }]
+ }
}
| 19 | Fix .eslintrc.json indent | 19 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
640 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- "node"
- "8"
- "10"
- "12"
- "14"
before_install:
- pip install --user codecov
after_success:
- codecov --file coverage/lcov.info --disable search
<MSG> remove old (no longer supported) versions of node.js from .travis.yml file; fixes #237
<DFF> @@ -1,11 +1,6 @@
language: node_js
node_js:
- - "node"
- - "8"
- - "10"
- "12"
- "14"
-before_install:
- - pip install --user codecov
after_success:
- - codecov --file coverage/lcov.info --disable search
+ - bash <(curl -s https://codecov.io/bash)
| 1 | remove old (no longer supported) versions of node.js from .travis.yml file; fixes #237 | 6 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
641 | <NME> .travis.yml
<BEF> language: node_js
node_js:
- "node"
- "8"
- "10"
- "12"
- "14"
before_install:
- pip install --user codecov
after_success:
- codecov --file coverage/lcov.info --disable search
<MSG> remove old (no longer supported) versions of node.js from .travis.yml file; fixes #237
<DFF> @@ -1,11 +1,6 @@
language: node_js
node_js:
- - "node"
- - "8"
- - "10"
- "12"
- "14"
-before_install:
- - pip install --user codecov
after_success:
- - codecov --file coverage/lcov.info --disable search
+ - bash <(curl -s https://codecov.io/bash)
| 1 | remove old (no longer supported) versions of node.js from .travis.yml file; fixes #237 | 6 | .yml | travis | apache-2.0 | dwyl/aws-sdk-mock |
642 | <NME> workflow.yml
<BEF> name: Node CI
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: [12.x, 14.x, 16.x, 18.x]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm i
- run: npm test
<MSG> ci: add a lint task to ci
<DFF> @@ -15,4 +15,5 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- run: npm i
+ - run: npm run lint
- run: npm test
| 1 | ci: add a lint task to ci | 0 | .yml | github/workflows/workflow | apache-2.0 | dwyl/aws-sdk-mock |
643 | <NME> workflow.yml
<BEF> name: Node CI
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: [12.x, 14.x, 16.x, 18.x]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm i
- run: npm test
<MSG> ci: add a lint task to ci
<DFF> @@ -15,4 +15,5 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- run: npm i
+ - run: npm run lint
- run: npm test
| 1 | ci: add a lint task to ci | 0 | .yml | github/workflows/workflow | apache-2.0 | dwyl/aws-sdk-mock |
644 | <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> Add test of request.on
<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 | Add test of request.on | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
645 | <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> Add test of request.on
<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 | Add test of request.on | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
646 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](https://nodei.co/npm/aws-sdk-mock/)
-->
This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked.
If you are *new* to Amazon WebServices Lambda
(*or need a refresher*),
please checkout our our
***Beginners Guide to AWS Lambda***:
<https://github.com/dwyl/learn-aws-lambda>
* [Why](#why)
* [What](#what)
* [Getting Started](#how)
* [Documentation](#documentation)
* [Background Reading](#background-reading)
## Why?
Testing your code is *essential* everywhere you need *reliability*.
Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK.
## What?
Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods.
## *How*? (*Usage*)
### *install* `aws-sdk-mock` from NPM
```sh
npm install aws-sdk-mock --save-dev
```
### Use in your Tests
#### Using plain JavaScript
```js
const AWS = require('aws-sdk-mock');
AWS.mock('DynamoDB', 'putItem', function (params, callback){
callback(null, 'successfully put item in database');
});
AWS.mock('SNS', 'publish', 'test-message');
// S3 getObject mock - return a Buffer object with file data
AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));
/**
TESTS
**/
AWS.restore('SNS', 'publish');
AWS.restore('DynamoDB');
AWS.restore('S3');
// or AWS.restore(); this will restore all the methods and services
```
#### Using TypeScript
```typescript
import AWSMock from 'aws-sdk-mock';
import AWS from 'aws-sdk';
import { GetItemInput } from 'aws-sdk/clients/dynamodb';
beforeAll(async (done) => {
//get requires env vars
done();
});
describe('the module', () => {
/**
TESTS below here
**/
it('should mock getItem from DynamoDB', async () => {
// Overwriting DynamoDB.getItem()
AWSMock.setSDKInstance(AWS);
AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => {
console.log('DynamoDB', 'getItem', 'mock called');
callback(null, {pk: 'foo', sk: 'bar'});
})
const input:GetItemInput = { TableName: '', Key: {} };
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });
AWSMock.restore('DynamoDB');
});
it('should mock reading from DocumentClient', async () => {
// Overwriting DynamoDB.DocumentClient.get()
AWSMock.setSDKInstance(AWS);
AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => {
console.log('DynamoDB.DocumentClient', 'get', 'mock called');
callback(null, {pk: 'foo', sk: 'bar'});
});
const input:GetItemInput = { TableName: '', Key: {} };
const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });
AWSMock.restore('DynamoDB.DocumentClient');
});
});
```
#### Sinon
You can also pass Sinon spies to the mock:
```js
const updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
// Object under test
myDynamoManager.scaleDownTable();
// Assert on your Sinon spy as normal
assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK');
const expectedParams = {
TableName: 'testTableName',
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters');
```
**NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked.
Example 1:
```js
const AWS = require('aws-sdk');
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
exports.handler = function(event, context) {
// do something with the services e.g. sns.publish
}
```
Example 2:
```js
const AWS = require('aws-sdk');
exports.handler = function(event, context) {
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
}
```
Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either.
Example 1 (won't work):
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
### Configuring promises
}
```
Example 2 (will work):
```js
exports.handler = function(event, context) {
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
someAsyncFunction(() => {
// do something with the services e.g. sns.publish
});
}
```
### Nested services
It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods:
```js
AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, {Item: {Key: 'Value'}});
});
```
**NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent:
```js
// OK
AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
AWS.mock('DynamoDB', 'describeTable', 'message');
AWS.restore('DynamoDB');
AWS.restore('DynamoDB.DocumentClient');
// Not OK
AWS.mock('DynamoDB', 'describeTable', 'message');
AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
// Not OK
AWS.restore('DynamoDB.DocumentClient');
AWS.restore('DynamoDB');
```
### Don't worry about the constructor configuration
Some constructors of the aws-sdk will require you to pass through a configuration object.
```js
const csd = new AWS.CloudSearchDomain({
endpoint: 'your.end.point',
region: 'eu-west'
});
```
Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this.
**aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br>
If configurations errors still occur it means you passed wrong configuration in your implementation.
### Setting the `aws-sdk` module explicitly
Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`.
Example:
```js
const path = require('path');
const AWS = require('aws-sdk-mock');
AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
/**
TESTS
**/
```
### Setting the `aws-sdk` object explicitly
Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`.
Example:
```js
// test code
const AWSMock = require('aws-sdk-mock');
import AWS from 'aws-sdk';
AWSMock.setSDKInstance(AWS);
AWSMock.mock('SQS', /* ... */);
// implementation code
const sqs = new AWS.SQS();
```
### Configuring promises
If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library.
Example (if Q is your promise library of choice):
```js
const AWS = require('aws-sdk-mock'),
Q = require('q');
AWS.Promise = Q.Promise;
/**
TESTS
**/
```
## Documentation
### `AWS.mock(service, method, replace)`
Replaces a method on an AWS service with a replacement function or string.
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 |
| `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' |
| `replace` | string or function | Required | A string or function to replace the method |
### `AWS.restore(service, method)`
Removes the mock to restore the specified AWS service
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored |
| `method` | string | Optional | Method on AWS service to restore |
If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored
i.e. equivalent to a 'restore all' function.
### `AWS.remock(service, method, replace)`
Updates the `replace` method on an existing mocked service.
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 |
| `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' |
| `replace` | string or function | Required | A string or function to replace the method |
### `AWS.setSDK(path)`
Explicitly set the require path for the `aws-sdk`
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `path` | string | Required | Path to a nested AWS SDK node module |
### `AWS.setSDKInstance(sdk)`
Explicitly set the `aws-sdk` instance to use
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `sdk` | object | Required | The AWS SDK object |
## Background Reading
* [Mocking using Sinon.js](http://sinonjs.org/docs/)
* [AWS Lambda](https://github.com/dwyl/learn-aws-lambda)
**Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving**
<MSG> Add missing closing code block end to README
<DFF> @@ -178,6 +178,7 @@ var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
+```
### Configuring promises
| 1 | Add missing closing code block end to README | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
647 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](https://nodei.co/npm/aws-sdk-mock/)
-->
This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked.
If you are *new* to Amazon WebServices Lambda
(*or need a refresher*),
please checkout our our
***Beginners Guide to AWS Lambda***:
<https://github.com/dwyl/learn-aws-lambda>
* [Why](#why)
* [What](#what)
* [Getting Started](#how)
* [Documentation](#documentation)
* [Background Reading](#background-reading)
## Why?
Testing your code is *essential* everywhere you need *reliability*.
Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK.
## What?
Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods.
## *How*? (*Usage*)
### *install* `aws-sdk-mock` from NPM
```sh
npm install aws-sdk-mock --save-dev
```
### Use in your Tests
#### Using plain JavaScript
```js
const AWS = require('aws-sdk-mock');
AWS.mock('DynamoDB', 'putItem', function (params, callback){
callback(null, 'successfully put item in database');
});
AWS.mock('SNS', 'publish', 'test-message');
// S3 getObject mock - return a Buffer object with file data
AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));
/**
TESTS
**/
AWS.restore('SNS', 'publish');
AWS.restore('DynamoDB');
AWS.restore('S3');
// or AWS.restore(); this will restore all the methods and services
```
#### Using TypeScript
```typescript
import AWSMock from 'aws-sdk-mock';
import AWS from 'aws-sdk';
import { GetItemInput } from 'aws-sdk/clients/dynamodb';
beforeAll(async (done) => {
//get requires env vars
done();
});
describe('the module', () => {
/**
TESTS below here
**/
it('should mock getItem from DynamoDB', async () => {
// Overwriting DynamoDB.getItem()
AWSMock.setSDKInstance(AWS);
AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => {
console.log('DynamoDB', 'getItem', 'mock called');
callback(null, {pk: 'foo', sk: 'bar'});
})
const input:GetItemInput = { TableName: '', Key: {} };
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });
AWSMock.restore('DynamoDB');
});
it('should mock reading from DocumentClient', async () => {
// Overwriting DynamoDB.DocumentClient.get()
AWSMock.setSDKInstance(AWS);
AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => {
console.log('DynamoDB.DocumentClient', 'get', 'mock called');
callback(null, {pk: 'foo', sk: 'bar'});
});
const input:GetItemInput = { TableName: '', Key: {} };
const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });
AWSMock.restore('DynamoDB.DocumentClient');
});
});
```
#### Sinon
You can also pass Sinon spies to the mock:
```js
const updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
// Object under test
myDynamoManager.scaleDownTable();
// Assert on your Sinon spy as normal
assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK');
const expectedParams = {
TableName: 'testTableName',
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters');
```
**NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked.
Example 1:
```js
const AWS = require('aws-sdk');
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
exports.handler = function(event, context) {
// do something with the services e.g. sns.publish
}
```
Example 2:
```js
const AWS = require('aws-sdk');
exports.handler = function(event, context) {
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
// do something with the services e.g. sns.publish
}
```
Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either.
Example 1 (won't work):
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
### Configuring promises
}
```
Example 2 (will work):
```js
exports.handler = function(event, context) {
const sns = AWS.SNS();
const dynamoDb = AWS.DynamoDB();
someAsyncFunction(() => {
// do something with the services e.g. sns.publish
});
}
```
### Nested services
It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods:
```js
AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, {Item: {Key: 'Value'}});
});
```
**NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent:
```js
// OK
AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
AWS.mock('DynamoDB', 'describeTable', 'message');
AWS.restore('DynamoDB');
AWS.restore('DynamoDB.DocumentClient');
// Not OK
AWS.mock('DynamoDB', 'describeTable', 'message');
AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
// Not OK
AWS.restore('DynamoDB.DocumentClient');
AWS.restore('DynamoDB');
```
### Don't worry about the constructor configuration
Some constructors of the aws-sdk will require you to pass through a configuration object.
```js
const csd = new AWS.CloudSearchDomain({
endpoint: 'your.end.point',
region: 'eu-west'
});
```
Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this.
**aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br>
If configurations errors still occur it means you passed wrong configuration in your implementation.
### Setting the `aws-sdk` module explicitly
Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`.
Example:
```js
const path = require('path');
const AWS = require('aws-sdk-mock');
AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
/**
TESTS
**/
```
### Setting the `aws-sdk` object explicitly
Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`.
Example:
```js
// test code
const AWSMock = require('aws-sdk-mock');
import AWS from 'aws-sdk';
AWSMock.setSDKInstance(AWS);
AWSMock.mock('SQS', /* ... */);
// implementation code
const sqs = new AWS.SQS();
```
### Configuring promises
If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library.
Example (if Q is your promise library of choice):
```js
const AWS = require('aws-sdk-mock'),
Q = require('q');
AWS.Promise = Q.Promise;
/**
TESTS
**/
```
## Documentation
### `AWS.mock(service, method, replace)`
Replaces a method on an AWS service with a replacement function or string.
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 |
| `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' |
| `replace` | string or function | Required | A string or function to replace the method |
### `AWS.restore(service, method)`
Removes the mock to restore the specified AWS service
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored |
| `method` | string | Optional | Method on AWS service to restore |
If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored
i.e. equivalent to a 'restore all' function.
### `AWS.remock(service, method, replace)`
Updates the `replace` method on an existing mocked service.
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 |
| `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' |
| `replace` | string or function | Required | A string or function to replace the method |
### `AWS.setSDK(path)`
Explicitly set the require path for the `aws-sdk`
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `path` | string | Required | Path to a nested AWS SDK node module |
### `AWS.setSDKInstance(sdk)`
Explicitly set the `aws-sdk` instance to use
| Param | Type | Optional/Required | Description |
| :------------- | :------------- | :------------- | :------------- |
| `sdk` | object | Required | The AWS SDK object |
## Background Reading
* [Mocking using Sinon.js](http://sinonjs.org/docs/)
* [AWS Lambda](https://github.com/dwyl/learn-aws-lambda)
**Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving**
<MSG> Add missing closing code block end to README
<DFF> @@ -178,6 +178,7 @@ var AWS = require('aws-sdk-mock');
var AWS_SDK = require('aws-sdk')
AWS.setSDKInstance(AWS_SDK);
+```
### Configuring promises
| 1 | Add missing closing code block end to README | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
648 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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 Buffer object with file data
awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv")));
/**
TESTS
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> Merge pull request #126 from capaj/patch-1
changed new Buffer to Buffer.from
<DFF> @@ -53,8 +53,9 @@ 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", new Buffer(require("fs").readFileSync("testFile.csv")));
+// S3 getObject mock - return a Bffer object with file data
+awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv")));
+
/**
TESTS
| 3 | Merge pull request #126 from capaj/patch-1 | 2 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
649 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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 Buffer object with file data
awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv")));
/**
TESTS
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> Merge pull request #126 from capaj/patch-1
changed new Buffer to Buffer.from
<DFF> @@ -53,8 +53,9 @@ 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", new Buffer(require("fs").readFileSync("testFile.csv")));
+// S3 getObject mock - return a Bffer object with file data
+awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv")));
+
/**
TESTS
| 3 | Merge pull request #126 from capaj/patch-1 | 2 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
650 | <NME> .eslintrc.json
<BEF> ADDFILE
<MSG> Add .eslintrc.json
https://github.com/aws/aws-sdk-js/blob/master/.eslintrc
<DFF> @@ -0,0 +1,23 @@
+{
+ "env": {
+ "browser": true,
+ "node": true
+ },
+ "globals": {
+ "Buffer": true,
+ "escape": true
+ },
+ "rules": {
+ "quotes": [2, "single"],
+ "strict": 0,
+ "curly": 0,
+ "no-empty": 0,
+ "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": 0
+ }
+}
| 23 | Add .eslintrc.json | 0 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
651 | <NME> .eslintrc.json
<BEF> ADDFILE
<MSG> Add .eslintrc.json
https://github.com/aws/aws-sdk-js/blob/master/.eslintrc
<DFF> @@ -0,0 +1,23 @@
+{
+ "env": {
+ "browser": true,
+ "node": true
+ },
+ "globals": {
+ "Buffer": true,
+ "escape": true
+ },
+ "rules": {
+ "quotes": [2, "single"],
+ "strict": 0,
+ "curly": 0,
+ "no-empty": 0,
+ "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": 0
+ }
+}
| 23 | Add .eslintrc.json | 0 | .json | eslintrc | apache-2.0 | dwyl/aws-sdk-mock |
652 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
const test = tap.test;
const awsMock = require('../index.js');
const AWS = require('aws-sdk');
const isNodeStream = require('is-node-stream');
const concatStream = require('concat-stream');
const Readable = require('stream').Readable;
const jest = require('jest-mock');
const sinon = require('sinon');
AWS.config.paramValidation = false;
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
})
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
})
})
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
var s3 = new AWS.S3();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
callback(null, options);
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equal(data.test, 'message');
st.end();
});
});
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
st.end();
});
});
t.test('method with no input rules can be mocked even if paramValidation is set', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
t.test('method succeeds on valid input when paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equal(data.Body, 'body');
st.end();
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
})
})
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
st.equals(data, 'test');
awsMock.restore('SNS');
st.end();
})
})
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
const sns = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
lambda.createFunction({}, function(err, data) {
st.equals(data, 'message');
st.end();
})
});
});
if (typeof(Promise) === 'function') {
callback(null, 'message 1');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
sns1.subscribe({}, function(err, data){
st.equal(data, 'message 2');
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise()
}).catch(function(data){
st.equals(data, error);
st.end();
});
})
t.test('promises work with async completion', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.restore('Lambda', 'createFunction');
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();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise()
}).catch(function(data){
st.equals(data, error);
st.end();
});
})
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
const lambda = new AWS.Lambda();
});
var lambda = new AWS.Lambda();
function P(handler) {
var self = this
function yay (value) {
self.value = value
}
handler(yay, function(){})
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P)
var promise = lambda.getFunction({}).promise()
st.equals(promise.constructor.name, 'P')
promise.then(function(data) {
st.equals(data, 'message');
st.end();
});
})
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
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();
});
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();
}));
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
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('promises can be configured', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '')
awsMock.restore('S3', 'getObject');
st.end();
}));
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
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 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.
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");
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.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");
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', {});
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
var docClient = new AWS.DynamoDB.DocumentClient();
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();
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
})
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
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.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
})
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
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');
st.equals(data, 'message');
});
st.end();
})
t.test('Mocked service should return the sinon stub', function(st) {
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
st.equal(AWS.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('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e)
}
});
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');
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');
awsMock.restore()
st.end();
});
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
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();
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
st.equals(data, 'message2');
awsMock.restore('SNS');
st.end();
})
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
var bad = {}
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message')
});
awsMock.setSDKInstance(AWS);
awsMock.restore()
st.end();
});
t.end();
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> Fix add semicolon
Added a semicolon at the end of the sentence
<DFF> @@ -14,7 +14,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
+ });
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
@@ -25,8 +25,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
- })
+ });
+ });
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
var s3 = new AWS.S3();
@@ -83,8 +83,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
- })
+ });
+ });
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
@@ -97,8 +97,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'test');
awsMock.restore('SNS');
st.end();
- })
- })
+ });
+ });
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
@@ -112,7 +112,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
lambda.createFunction({}, function(err, data) {
st.equals(data, 'message');
st.end();
- })
+ });
});
});
if (typeof(Promise) === 'function') {
@@ -130,12 +130,12 @@ test('AWS.mock function should mock AWS service and method on the service', func
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
- return lambda.createFunction({}).promise()
+ return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(data, error);
st.end();
});
- })
+ });
t.test('promises work with async completion', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.restore('Lambda', 'createFunction');
@@ -150,12 +150,12 @@ test('AWS.mock function should mock AWS service and method on the service', func
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
- return lambda.createFunction({}).promise()
+ return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(data, error);
st.end();
});
- })
+ });
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
@@ -163,21 +163,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
var lambda = new AWS.Lambda();
function P(handler) {
- var self = this
+ var self = this;
function yay (value) {
- self.value = value
+ self.value = value;
}
- handler(yay, function(){})
+ handler(yay, function(){});
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
- AWS.config.setPromisesDependency(P)
- var promise = lambda.getFunction({}).promise()
- st.equals(promise.constructor.name, 'P')
+ AWS.config.setPromisesDependency(P);
+ var promise = lambda.getFunction({}).promise();
+ st.equals(promise.constructor.name, 'P');
promise.then(function(data) {
st.equals(data, 'message');
st.end();
});
- })
+ });
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
@@ -202,7 +202,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body')
+ st.equals(actual.toString(), 'body');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -213,7 +213,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body')
+ st.equals(actual.toString(), 'body');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -224,7 +224,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '')
+ st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -235,7 +235,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '')
+ st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -251,7 +251,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
- })
+ });
t.test('only the method on the service is restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
@@ -265,7 +265,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
- })
+ });
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
@@ -296,7 +296,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
- })
+ });
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
var docClient = new AWS.DynamoDB.DocumentClient();
@@ -325,7 +325,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
- })
+ });
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
@@ -340,7 +340,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
- })
+ });
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
@@ -405,7 +405,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
});
st.end();
- })
+ });
t.test('Mocked service should return the sinon stub', function(st) {
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
@@ -420,7 +420,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
- console.log(e)
+ console.log(e);
}
});
@@ -435,16 +435,16 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
+ });
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
- awsMock.mock('SNS', 'publish', 'message')
+ awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
- awsMock.restore()
+ awsMock.restore();
st.end();
});
@@ -453,7 +453,7 @@ 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')
+ var aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
var sns = new AWS.SNS();
@@ -461,17 +461,17 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
st.equals(data, 'message2');
awsMock.restore('SNS');
st.end();
- })
+ });
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
- var bad = {}
+ var bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
- awsMock.mock('SNS', 'publish', 'message')
+ awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
- awsMock.restore()
+ awsMock.restore();
st.end();
});
t.end();
| 38 | Fix add semicolon | 38 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
653 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
const test = tap.test;
const awsMock = require('../index.js');
const AWS = require('aws-sdk');
const isNodeStream = require('is-node-stream');
const concatStream = require('concat-stream');
const Readable = require('stream').Readable;
const jest = require('jest-mock');
const sinon = require('sinon');
AWS.config.paramValidation = false;
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
})
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
})
})
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
var s3 = new AWS.S3();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
callback(null, options);
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equal(data.test, 'message');
st.end();
});
});
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
st.end();
});
});
t.test('method with no input rules can be mocked even if paramValidation is set', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
t.test('method succeeds on valid input when paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equal(data.Body, 'body');
st.end();
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
})
})
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
st.equals(data, 'test');
awsMock.restore('SNS');
st.end();
})
})
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 1');
});
const sns = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
lambda.createFunction({}, function(err, data) {
st.equals(data, 'message');
st.end();
})
});
});
if (typeof(Promise) === 'function') {
callback(null, 'message 1');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
awsMock.remock('SNS', 'subscribe', function(params, callback){
callback(null, 'message 2');
});
sns1.subscribe({}, function(err, data){
st.equal(data, 'message 2');
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise()
}).catch(function(data){
st.equals(data, error);
st.end();
});
})
t.test('promises work with async completion', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.restore('Lambda', 'createFunction');
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();
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
return lambda.createFunction({}).promise()
}).catch(function(data){
st.equals(data, error);
st.end();
});
})
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
const lambda = new AWS.Lambda();
});
var lambda = new AWS.Lambda();
function P(handler) {
var self = this
function yay (value) {
self.value = value
}
handler(yay, function(){})
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P)
var promise = lambda.getFunction({}).promise()
st.equals(promise.constructor.name, 'P')
promise.then(function(data) {
st.equals(data, 'message');
st.end();
});
})
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
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();
});
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();
}));
});
const lambda = new AWS.Lambda();
lambda.getFunction({}).promise().then(function(data) {
st.equal(data, 'message');
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('promises can be configured', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
});
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
st.equals(actual.toString(), '')
awsMock.restore('S3', 'getObject');
st.end();
}));
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
AWS.config.setPromisesDependency(P);
const promise = lambda.getFunction({}).promise();
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 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.
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");
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.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");
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', {});
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
var docClient = new AWS.DynamoDB.DocumentClient();
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();
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
})
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
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.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
})
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
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');
st.equals(data, 'message');
});
st.end();
})
t.test('Mocked service should return the sinon stub', function(st) {
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
st.equal(AWS.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('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e)
}
});
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');
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');
awsMock.restore()
st.end();
});
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
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();
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
st.equals(data, 'message2');
awsMock.restore('SNS');
st.end();
})
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
var bad = {}
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message')
});
awsMock.setSDKInstance(AWS);
awsMock.restore()
st.end();
});
t.end();
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> Fix add semicolon
Added a semicolon at the end of the sentence
<DFF> @@ -14,7 +14,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
+ });
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
@@ -25,8 +25,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
- })
+ });
+ });
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
var s3 = new AWS.S3();
@@ -83,8 +83,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
- })
+ });
+ });
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
@@ -97,8 +97,8 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'test');
awsMock.restore('SNS');
st.end();
- })
- })
+ });
+ });
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
@@ -112,7 +112,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
lambda.createFunction({}, function(err, data) {
st.equals(data, 'message');
st.end();
- })
+ });
});
});
if (typeof(Promise) === 'function') {
@@ -130,12 +130,12 @@ test('AWS.mock function should mock AWS service and method on the service', func
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
- return lambda.createFunction({}).promise()
+ return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(data, error);
st.end();
});
- })
+ });
t.test('promises work with async completion', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.restore('Lambda', 'createFunction');
@@ -150,12 +150,12 @@ test('AWS.mock function should mock AWS service and method on the service', func
lambda.getFunction({}).promise().then(function(data) {
st.equals(data, 'message');
}).then(function(){
- return lambda.createFunction({}).promise()
+ return lambda.createFunction({}).promise();
}).catch(function(data){
st.equals(data, error);
st.end();
});
- })
+ });
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
@@ -163,21 +163,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
var lambda = new AWS.Lambda();
function P(handler) {
- var self = this
+ var self = this;
function yay (value) {
- self.value = value
+ self.value = value;
}
- handler(yay, function(){})
+ handler(yay, function(){});
}
P.prototype.then = function(yay) { if (this.value) yay(this.value) };
- AWS.config.setPromisesDependency(P)
- var promise = lambda.getFunction({}).promise()
- st.equals(promise.constructor.name, 'P')
+ AWS.config.setPromisesDependency(P);
+ var promise = lambda.getFunction({}).promise();
+ st.equals(promise.constructor.name, 'P');
promise.then(function(data) {
st.equals(data, 'message');
st.end();
});
- })
+ });
}
t.test('request object supports createReadStream', function(st) {
awsMock.mock('S3', 'getObject', 'body');
@@ -202,7 +202,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body')
+ st.equals(actual.toString(), 'body');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -213,7 +213,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), 'body')
+ st.equals(actual.toString(), 'body');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -224,7 +224,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '')
+ st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -235,7 +235,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
stream.pipe(concatStream(function(actual) {
- st.equals(actual.toString(), '')
+ st.equals(actual.toString(), '');
awsMock.restore('S3', 'getObject');
st.end();
}));
@@ -251,7 +251,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.end();
- })
+ });
t.test('only the method on the service is restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
@@ -265,7 +265,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
- })
+ });
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
@@ -296,7 +296,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
- })
+ });
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
var docClient = new AWS.DynamoDB.DocumentClient();
@@ -325,7 +325,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
- })
+ });
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
@@ -340,7 +340,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'query');
st.end();
- })
+ });
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
@@ -405,7 +405,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(data, 'message');
});
st.end();
- })
+ });
t.test('Mocked service should return the sinon stub', function(st) {
var stub = awsMock.mock('CloudSearchDomain', 'search');
st.equals(stub.stub.isSinonProxy, true);
@@ -420,7 +420,7 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
- console.log(e)
+ console.log(e);
}
});
@@ -435,16 +435,16 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) {
st.equals(data, 'message');
awsMock.restore('SNS');
st.end();
- })
+ });
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
- awsMock.mock('SNS', 'publish', 'message')
+ awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
- awsMock.restore()
+ awsMock.restore();
st.end();
});
@@ -453,7 +453,7 @@ 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')
+ var aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
var sns = new AWS.SNS();
@@ -461,17 +461,17 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t
st.equals(data, 'message2');
awsMock.restore('SNS');
st.end();
- })
+ });
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
- var bad = {}
+ var bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
- awsMock.mock('SNS', 'publish', 'message')
+ awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
- awsMock.restore()
+ awsMock.restore();
st.end();
});
t.end();
| 38 | Fix add semicolon | 38 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
654 | <NME> index.test-d.ts
<BEF> import * as AWS from 'aws-sdk';
import { AWSError } from 'aws-sdk';
import { ListObjectsV2Request } from 'aws-sdk/clients/s3';
import { expectError, expectType } from 'tsd';
import { mock, remock, restore, setSDK, setSDKInstance } from '../index';
const awsError: AWSError = {
name: 'AWSError',
message: 'message',
code: 'code',
time: new Date(),
};
/**
* mock
*/
expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => {
expectType<ListObjectsV2Request>(params);
const output: AWS.S3.ListObjectsV2Output = {
Name: params.Bucket,
MaxKeys: params.MaxKeys,
Delimiter: params.Delimiter,
Prefix: params.Prefix,
KeyCount: 1,
IsTruncated: false,
ContinuationToken: params.ContinuationToken,
Contents: [
{
LastModified: new Date(),
ETag: '"668d791b0c7d6a7f0f86c269888b4546"',
StorageClass: 'STANDARD',
Key: 'aws-sdk-mock/index.js',
Size: 8524,
},
]
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectType<void>(remock('EC2', 'stopInstances', (params, callback) => {
// $ExpectType string[]
const instanceIds = params.InstanceIds;
expectType<string[]>(instanceIds);
const output: AWS.EC2.StopInstancesResult = {
StoppingInstances: instanceIds.map(id => ({
InstanceId: id,
PreviousState: { Name: 'running' },
CurrentState: { Name: 'stopping' },
})),
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
/**
* Remock
*/
expectType<void>(remock('Snowball', 'makeRequest', undefined));
expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined));
expectError(remock('Snowball', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentServer', 'get', undefined));
/**
* Restore
*/
expectType<void>(restore('Pricing', 'getProducts'));
expectType<void>(restore('DynamoDB.DocumentClient', 'get'));
expectError(restore('Pricing', 'borrowMoney'));
expectError(restore('DynamoDB.DocumentClient', 'unknown'));
expectType<void>(restore('KMS'));
expectType<void>(restore('DynamoDB.DocumentClient'));
expectError(restore('Skynet'));
expectError(restore('DynamoDB.DocumentServer'));
expectError(restore(42));
expectType<void>(restore());
expectError(restore(null));
/**
* setSDK
*/
expectType<void>(setSDK('aws-sdk'));
/**
* setSDKInstance
*/
expectType<void>(setSDKInstance(AWS));
expectError(setSDKInstance(import('aws-sdk')));
async function foo() {
expectType<void>(setSDKInstance(await import('aws-sdk')));
}
expectError(setSDKInstance(AWS.S3));
import allClients = require('aws-sdk/clients/all');
expectError(setSDKInstance(allClients));
<MSG> #259: patch nested client names
<DFF> @@ -51,6 +51,10 @@ expectError(mock('S3', 'describeObjects', (params, callback) => {
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
+expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen'));
+
+expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen'));
+expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
| 4 | #259: patch nested client names | 0 | .ts | test-d | apache-2.0 | dwyl/aws-sdk-mock |
655 | <NME> index.test-d.ts
<BEF> import * as AWS from 'aws-sdk';
import { AWSError } from 'aws-sdk';
import { ListObjectsV2Request } from 'aws-sdk/clients/s3';
import { expectError, expectType } from 'tsd';
import { mock, remock, restore, setSDK, setSDKInstance } from '../index';
const awsError: AWSError = {
name: 'AWSError',
message: 'message',
code: 'code',
time: new Date(),
};
/**
* mock
*/
expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => {
expectType<ListObjectsV2Request>(params);
const output: AWS.S3.ListObjectsV2Output = {
Name: params.Bucket,
MaxKeys: params.MaxKeys,
Delimiter: params.Delimiter,
Prefix: params.Prefix,
KeyCount: 1,
IsTruncated: false,
ContinuationToken: params.ContinuationToken,
Contents: [
{
LastModified: new Date(),
ETag: '"668d791b0c7d6a7f0f86c269888b4546"',
StorageClass: 'STANDARD',
Key: 'aws-sdk-mock/index.js',
Size: 8524,
},
]
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
expectType<void>(remock('EC2', 'stopInstances', (params, callback) => {
// $ExpectType string[]
const instanceIds = params.InstanceIds;
expectType<string[]>(instanceIds);
const output: AWS.EC2.StopInstancesResult = {
StoppingInstances: instanceIds.map(id => ({
InstanceId: id,
PreviousState: { Name: 'running' },
CurrentState: { Name: 'stopping' },
})),
};
expectType<void>(callback(undefined, output));
expectType<void>(callback(undefined, {}));
expectError(callback(null, output));
expectError(callback(undefined));
expectType<void>(callback(awsError));
expectError(callback(awsError, output));
}));
/**
* Remock
*/
expectType<void>(remock('Snowball', 'makeRequest', undefined));
expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined));
expectError(remock('Snowball', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined));
expectError(remock('DynamoDB.DocumentServer', 'get', undefined));
/**
* Restore
*/
expectType<void>(restore('Pricing', 'getProducts'));
expectType<void>(restore('DynamoDB.DocumentClient', 'get'));
expectError(restore('Pricing', 'borrowMoney'));
expectError(restore('DynamoDB.DocumentClient', 'unknown'));
expectType<void>(restore('KMS'));
expectType<void>(restore('DynamoDB.DocumentClient'));
expectError(restore('Skynet'));
expectError(restore('DynamoDB.DocumentServer'));
expectError(restore(42));
expectType<void>(restore());
expectError(restore(null));
/**
* setSDK
*/
expectType<void>(setSDK('aws-sdk'));
/**
* setSDKInstance
*/
expectType<void>(setSDKInstance(AWS));
expectError(setSDKInstance(import('aws-sdk')));
async function foo() {
expectType<void>(setSDKInstance(await import('aws-sdk')));
}
expectError(setSDKInstance(AWS.S3));
import allClients = require('aws-sdk/clients/all');
expectError(setSDKInstance(allClients));
<MSG> #259: patch nested client names
<DFF> @@ -51,6 +51,10 @@ expectError(mock('S3', 'describeObjects', (params, callback) => {
}));
expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen'));
+expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen'));
+
+expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen'));
+expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen'));
expectError(mock('StaticDB', 'getItem', "it couldn't"));
| 4 | #259: patch nested client names | 0 | .ts | test-d | apache-2.0 | dwyl/aws-sdk-mock |
656 | <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');
});
})
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('method on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all methods on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> fix(paramValidation): fix Cannot read property 'operations' of undefined error when param validation is set
<DFF> @@ -327,6 +327,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
})
});
+ t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
+ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
+ callback(null, 'test');
+ });
+ var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
+
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(docClient.query.isSinonProxy, true);
+ docClient.query({}, function(err, data){
+ console.warn(err);
+ st.equals(data, 'test');
+ awsMock.restore('DynamoDB.DocumentClient', 'query');
+ st.end();
+ })
+ });
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
| 15 | fix(paramValidation): fix Cannot read property 'operations' of undefined error when param validation is set | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
657 | <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');
});
})
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('method on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS', 'publish');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all methods on all service instances are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> fix(paramValidation): fix Cannot read property 'operations' of undefined error when param validation is set
<DFF> @@ -327,6 +327,21 @@ test('AWS.mock function should mock AWS service and method on the service', func
});
})
});
+ t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
+ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
+ callback(null, 'test');
+ });
+ var docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
+
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(docClient.query.isSinonProxy, true);
+ docClient.query({}, function(err, data){
+ console.warn(err);
+ st.equals(data, 'test');
+ awsMock.restore('DynamoDB.DocumentClient', 'query');
+ st.end();
+ })
+ });
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
| 15 | fix(paramValidation): fix Cannot read property 'operations' of undefined error when param validation is set | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
658 | <NME> workflow.yml
<BEF> ADDFILE
<MSG> ci: add .github/workflows/workflow.yml
<DFF> @@ -0,0 +1,18 @@
+name: Node CI
+
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ node-version: [12.x, 14.x, 16.x]
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions/setup-node@v2
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: npm i
+ - run: npm test
| 18 | ci: add .github/workflows/workflow.yml | 0 | .yml | github/workflows/workflow | apache-2.0 | dwyl/aws-sdk-mock |
659 | <NME> workflow.yml
<BEF> ADDFILE
<MSG> ci: add .github/workflows/workflow.yml
<DFF> @@ -0,0 +1,18 @@
+name: Node CI
+
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ node-version: [12.x, 14.x, 16.x]
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions/setup-node@v2
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: npm i
+ - run: npm test
| 18 | ci: add .github/workflows/workflow.yml | 0 | .yml | github/workflows/workflow | apache-2.0 | dwyl/aws-sdk-mock |
660 | <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('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 pull request #138 from abetomo/remove_unnecessary_variable
Clean the test code
<DFF> @@ -270,7 +270,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');
@@ -386,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);
@@ -441,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();
| 1 | Merge pull request #138 from abetomo/remove_unnecessary_variable | 3 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
661 | <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('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 pull request #138 from abetomo/remove_unnecessary_variable
Clean the test code
<DFF> @@ -270,7 +270,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');
@@ -386,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);
@@ -441,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();
| 1 | Merge pull request #138 from abetomo/remove_unnecessary_variable | 3 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
662 | <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.equals(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
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 #224 from TastefulElk/test/increase-coverage
improve test coverage to 100%
<DFF> @@ -469,9 +469,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(stub.stub.isSinonProxy, true);
st.end();
});
+
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
+ awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
| 2 | Merge pull request #224 from TastefulElk/test/increase-coverage | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
663 | <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.equals(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
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 #224 from TastefulElk/test/increase-coverage
improve test coverage to 100%
<DFF> @@ -469,9 +469,11 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(stub.stub.isSinonProxy, true);
st.end();
});
+
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
+ awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
| 2 | Merge pull request #224 from TastefulElk/test/increase-coverage | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
664 | <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){
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.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
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> Added ability to mock nested services like DynamoDB.DocumentClient, though care must be taken when mocking a nested service and its parent.
<DFF> @@ -100,22 +100,100 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, "test");
});
+ awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
+ callback(null, "test");
+ });
var sns = new AWS.SNS();
+ var docClient = new AWS.DynamoDB.DocumentClient();
var dynamoDb = new AWS.DynamoDB();
st.equals(AWS.SNS.isSinonProxy, true);
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(sns.publish.isSinonProxy, true);
+ st.equals(docClient.put.isSinonProxy, true);
st.equals(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
+ t.test('a nested service can be mocked properly', function(st){
+ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
+ var docClient = new AWS.DynamoDB.DocumentClient();
+ awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
+ callback(null, 'test');
+ });
+ awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
+ callback(null, 'test');
+ });
+
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(docClient.put.isSinonProxy, true);
+ st.equals(docClient.get.isSinonProxy, true);
+
+ docClient.put({}, function(err, data){
+ st.equals(data, 'message');
+ docClient.get({}, function(err, data){
+ st.equals(data, 'test');
+
+ awsMock.restore('DynamoDB.DocumentClient', 'get');
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+
+ awsMock.restore('DynamoDB.DocumentClient');
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
+ 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');
+ var docClient = new AWS.DynamoDB.DocumentClient();
+ var dynamoDb = new AWS.DynamoDB();
+
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(AWS.DynamoDB.isSinonProxy, true);
+ st.equals(docClient.get.isSinonProxy, true);
+ st.equals(dynamoDb.getItem.isSinonProxy, true);
+
+ awsMock.restore('DynamoDB');
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.get.isSinonProxy, true);
+ 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);
+ st.equals(dynamoDb.getItem.isSinonProxy, true);
+
+ awsMock.restore('DynamoDB.DocumentClient');
+
+ // the first assertion is true because DynamoDB is still mocked
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
+ st.equals(AWS.DynamoDB.isSinonProxy, true);
+ st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+ st.equals(dynamoDb.getItem.isSinonProxy, true);
+
+ awsMock.restore('DynamoDB');
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
+ st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+ st.equals(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) {
| 78 | Added ability to mock nested services like DynamoDB.DocumentClient, though care must be taken when mocking a nested service and its parent. | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
665 | <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){
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.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
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> Added ability to mock nested services like DynamoDB.DocumentClient, though care must be taken when mocking a nested service and its parent.
<DFF> @@ -100,22 +100,100 @@ test('AWS.mock function should mock AWS service and method on the service', func
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, "test");
});
+ awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
+ callback(null, "test");
+ });
var sns = new AWS.SNS();
+ var docClient = new AWS.DynamoDB.DocumentClient();
var dynamoDb = new AWS.DynamoDB();
st.equals(AWS.SNS.isSinonProxy, true);
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equals(AWS.DynamoDB.isSinonProxy, true);
st.equals(sns.publish.isSinonProxy, true);
+ st.equals(docClient.put.isSinonProxy, true);
st.equals(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
})
+ t.test('a nested service can be mocked properly', function(st){
+ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
+ var docClient = new AWS.DynamoDB.DocumentClient();
+ awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
+ callback(null, 'test');
+ });
+ awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
+ callback(null, 'test');
+ });
+
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(docClient.put.isSinonProxy, true);
+ st.equals(docClient.get.isSinonProxy, true);
+
+ docClient.put({}, function(err, data){
+ st.equals(data, 'message');
+ docClient.get({}, function(err, data){
+ st.equals(data, 'test');
+
+ awsMock.restore('DynamoDB.DocumentClient', 'get');
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+
+ awsMock.restore('DynamoDB.DocumentClient');
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false);
+ 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');
+ var docClient = new AWS.DynamoDB.DocumentClient();
+ var dynamoDb = new AWS.DynamoDB();
+
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(AWS.DynamoDB.isSinonProxy, true);
+ st.equals(docClient.get.isSinonProxy, true);
+ st.equals(dynamoDb.getItem.isSinonProxy, true);
+
+ awsMock.restore('DynamoDB');
+ st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
+ st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.get.isSinonProxy, true);
+ 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);
+ st.equals(dynamoDb.getItem.isSinonProxy, true);
+
+ awsMock.restore('DynamoDB.DocumentClient');
+
+ // the first assertion is true because DynamoDB is still mocked
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
+ st.equals(AWS.DynamoDB.isSinonProxy, true);
+ st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+ st.equals(dynamoDb.getItem.isSinonProxy, true);
+
+ awsMock.restore('DynamoDB');
+ st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
+ st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
+ st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false);
+ st.equals(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) {
| 78 | Added ability to mock nested services like DynamoDB.DocumentClient, though care must be taken when mocking a nested service and its parent. | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
666 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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
```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');
});
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');
// or AWS.restore(); this will restore all the methods and services
```
You can also pass Sinon spies to the mock:
```js
```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> docs(readme.md): Give a full example in typescript
As the documentation lacked a full example and also a typescript snippet, I added them after spending hours of figuring out how-to ;)
<DFF> @@ -46,6 +46,7 @@ npm install aws-sdk-mock --save-dev
### Use in your Tests
+#### Using plain JavaScript
```js
var AWS = require('aws-sdk-mock');
@@ -70,6 +71,57 @@ AWS.restore('S3');
// or AWS.restore(); this will restore all the methods and services
```
+#### Using TypeScript
+
+```typescript
+import * as AWSMock from "aws-sdk-mock";
+import * as 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"});
+ })
+
+ 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) => {
+ console.log('DynamoDB.DocumentClient', 'get', 'mock called');
+ 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');
+ });
+});
+```
+
+#### Sinon
You can also pass Sinon spies to the mock:
```js
| 52 | docs(readme.md): Give a full example in typescript | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
667 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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
```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');
});
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');
// or AWS.restore(); this will restore all the methods and services
```
You can also pass Sinon spies to the mock:
```js
```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> docs(readme.md): Give a full example in typescript
As the documentation lacked a full example and also a typescript snippet, I added them after spending hours of figuring out how-to ;)
<DFF> @@ -46,6 +46,7 @@ npm install aws-sdk-mock --save-dev
### Use in your Tests
+#### Using plain JavaScript
```js
var AWS = require('aws-sdk-mock');
@@ -70,6 +71,57 @@ AWS.restore('S3');
// or AWS.restore(); this will restore all the methods and services
```
+#### Using TypeScript
+
+```typescript
+import * as AWSMock from "aws-sdk-mock";
+import * as 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"});
+ })
+
+ 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) => {
+ console.log('DynamoDB.DocumentClient', 'get', 'mock called');
+ 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');
+ });
+});
+```
+
+#### Sinon
You can also pass Sinon spies to the mock:
```js
| 52 | docs(readme.md): Give a full example in typescript | 0 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
668 | <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;
}
}
}
return (function invokeMock() {
// If the value of 'replace' is a function we call it with the arguments.
if(typeof(replace) === 'function') {
return replace.apply(replace, args);
for (const key in services[service].methodMocks) {
mockServiceMethod(service, client, key, services[service].methodMocks[key].replace);
};
var callback = args[args.length - 1];
return callback(null, replace);
}
})()
});
}
*/
function wrapTestStubReplaceFn(replace) {
if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) {
return replace;
}
return (params, cb) => {
// If only one argument is provided, it is the callback
if (!cb) {
cb = params;
params = {};
}
// Spy on the users callback so we can later on determine if it has been called in their replace
const cbSpy = sinon.spy(cb);
try {
// Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters
const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy);
// If the users replace already called the callback, there's no more need for us do it.
if (cbSpy.called) {
return;
}
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
cb(undefined, result);
}
} catch (err) {
cb(err);
}
};
}
/**
* Stubs the method on a service.
*
* All AWS service methods take two argument:
* - params: an object.
* - callback: of the form 'function(err, data) {}'.
*/
function mockServiceMethod(service, client, method, replace) {
replace = wrapTestStubReplaceFn(replace);
services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() {
const args = Array.prototype.slice.call(arguments);
let userArgs, userCallback;
if (typeof args[(args.length || 1) - 1] === 'function') {
userArgs = args.slice(0, -1);
userCallback = args[(args.length || 1) - 1];
} else {
userArgs = args;
}
const havePromises = typeof AWS.Promise === 'function';
let promise, resolve, reject, storedResult;
const tryResolveFromStored = function() {
if (storedResult && promise) {
if (typeof storedResult.then === 'function') {
storedResult.then(resolve, reject)
} else if (storedResult.reject) {
reject(storedResult.reject);
} else {
resolve(storedResult.resolve);
}
}
};
const callback = function(err, data) {
if (!storedResult) {
if (err) {
storedResult = {reject: err};
} else {
storedResult = {resolve: data};
}
}
if (userCallback) {
userCallback(err, data);
}
tryResolveFromStored();
};
const request = {
promise: havePromises ? function() {
if (!promise) {
promise = new AWS.Promise(function (resolve_, reject_) {
resolve = resolve_;
reject = reject_;
});
}
tryResolveFromStored();
return promise;
} : undefined,
createReadStream: function() {
if (storedResult instanceof Readable) {
return storedResult;
}
if (replace instanceof Readable) {
return replace;
} else {
const stream = new Readable();
stream._read = function(size) {
if (typeof replace === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
};
return stream;
}
},
on: function(eventName, callback) {
return this;
},
send: function(callback) {
callback(storedResult.reject, storedResult.resolve);
}
};
// different locations for the paramValidation property
const config = (client.config || client.options || _AWS.config);
if (config.paramValidation) {
try {
// different strategies to find method, depending on wether the service is nested/unnested
const inputRules =
((client.api && client.api.operations[method]) || client[method] || {}).input;
if (inputRules) {
const params = userArgs[(userArgs.length || 1) - 1];
new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params);
}
} catch (e) {
callback(e, null);
return request;
}
}
// If the value of 'replace' is a function we call it with the arguments.
if (typeof replace === 'function') {
const result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
(typeof result.then === 'function' || result instanceof Readable)) {
storedResult = result
}
}
// Else we call the callback with the value of 'replace'.
else {
callback(null, replace);
}
return request;
});
}
/**
* Restores the mocks for just one method on a service, the entire service, or all mocks.
*
* When no parameters are passed, everything will be reset.
* When only the service is passed, that specific service will be reset.
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
if (!service) {
restoreAllServices();
} else {
if (method) {
restoreMethod(service, method);
} else {
restoreService(service);
}
};
};
/**
* Restores all mocked service and their corresponding methods.
*/
function restoreAllServices() {
for (const service in services) {
restoreService(service);
}
}
/**
* Restores a single mocked service and its corresponding methods.
*/
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
}
}
/**
* Restores all mocked methods on a service.
*/
function restoreAllMethods(service) {
for (const method in services[service].methodMocks) {
restoreMethod(service, method);
}
}
/**
* Restores a single mocked method on a service.
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
if (services[service].methodMocks[method].stub) {
// restore this method on all clients
services[service].clients.forEach(client => {
if (client[method] && typeof client[method].restore === 'function') {
client[method].restore();
}
})
}
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
}
}
(function() {
const setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
if (typeof setPromisesDependency === 'function') {
AWS.Promise = global.Promise;
_AWS.config.setPromisesDependency = function(p) {
AWS.Promise = p;
return setPromisesDependency(p);
};
}
})();
module.exports = AWS;
<MSG> Update index.js
<DFF> @@ -98,8 +98,10 @@ function mockServiceMethod(service, client, method, replace) {
}
}
}
-
- return (function invokeMock() {
+
+ return invokeMock()
+
+ function invokeMock() {
// If the value of 'replace' is a function we call it with the arguments.
if(typeof(replace) === 'function') {
return replace.apply(replace, args);
@@ -109,7 +111,7 @@ function mockServiceMethod(service, client, method, replace) {
var callback = args[args.length - 1];
return callback(null, replace);
}
- })()
+ }
});
}
| 5 | Update index.js | 3 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
669 | <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;
}
}
}
return (function invokeMock() {
// If the value of 'replace' is a function we call it with the arguments.
if(typeof(replace) === 'function') {
return replace.apply(replace, args);
for (const key in services[service].methodMocks) {
mockServiceMethod(service, client, key, services[service].methodMocks[key].replace);
};
var callback = args[args.length - 1];
return callback(null, replace);
}
})()
});
}
*/
function wrapTestStubReplaceFn(replace) {
if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) {
return replace;
}
return (params, cb) => {
// If only one argument is provided, it is the callback
if (!cb) {
cb = params;
params = {};
}
// Spy on the users callback so we can later on determine if it has been called in their replace
const cbSpy = sinon.spy(cb);
try {
// Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters
const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy);
// If the users replace already called the callback, there's no more need for us do it.
if (cbSpy.called) {
return;
}
if (typeof result.then === 'function') {
result.then(val => cb(undefined, val), err => cb(err));
} else {
cb(undefined, result);
}
} catch (err) {
cb(err);
}
};
}
/**
* Stubs the method on a service.
*
* All AWS service methods take two argument:
* - params: an object.
* - callback: of the form 'function(err, data) {}'.
*/
function mockServiceMethod(service, client, method, replace) {
replace = wrapTestStubReplaceFn(replace);
services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() {
const args = Array.prototype.slice.call(arguments);
let userArgs, userCallback;
if (typeof args[(args.length || 1) - 1] === 'function') {
userArgs = args.slice(0, -1);
userCallback = args[(args.length || 1) - 1];
} else {
userArgs = args;
}
const havePromises = typeof AWS.Promise === 'function';
let promise, resolve, reject, storedResult;
const tryResolveFromStored = function() {
if (storedResult && promise) {
if (typeof storedResult.then === 'function') {
storedResult.then(resolve, reject)
} else if (storedResult.reject) {
reject(storedResult.reject);
} else {
resolve(storedResult.resolve);
}
}
};
const callback = function(err, data) {
if (!storedResult) {
if (err) {
storedResult = {reject: err};
} else {
storedResult = {resolve: data};
}
}
if (userCallback) {
userCallback(err, data);
}
tryResolveFromStored();
};
const request = {
promise: havePromises ? function() {
if (!promise) {
promise = new AWS.Promise(function (resolve_, reject_) {
resolve = resolve_;
reject = reject_;
});
}
tryResolveFromStored();
return promise;
} : undefined,
createReadStream: function() {
if (storedResult instanceof Readable) {
return storedResult;
}
if (replace instanceof Readable) {
return replace;
} else {
const stream = new Readable();
stream._read = function(size) {
if (typeof replace === 'string' || Buffer.isBuffer(replace)) {
this.push(replace);
}
this.push(null);
};
return stream;
}
},
on: function(eventName, callback) {
return this;
},
send: function(callback) {
callback(storedResult.reject, storedResult.resolve);
}
};
// different locations for the paramValidation property
const config = (client.config || client.options || _AWS.config);
if (config.paramValidation) {
try {
// different strategies to find method, depending on wether the service is nested/unnested
const inputRules =
((client.api && client.api.operations[method]) || client[method] || {}).input;
if (inputRules) {
const params = userArgs[(userArgs.length || 1) - 1];
new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params);
}
} catch (e) {
callback(e, null);
return request;
}
}
// If the value of 'replace' is a function we call it with the arguments.
if (typeof replace === 'function') {
const result = replace.apply(replace, userArgs.concat([callback]));
if (storedResult === undefined && result != null &&
(typeof result.then === 'function' || result instanceof Readable)) {
storedResult = result
}
}
// Else we call the callback with the value of 'replace'.
else {
callback(null, replace);
}
return request;
});
}
/**
* Restores the mocks for just one method on a service, the entire service, or all mocks.
*
* When no parameters are passed, everything will be reset.
* When only the service is passed, that specific service will be reset.
* When a service and method are passed, only that method will be reset.
*/
AWS.restore = function(service, method) {
if (!service) {
restoreAllServices();
} else {
if (method) {
restoreMethod(service, method);
} else {
restoreService(service);
}
};
};
/**
* Restores all mocked service and their corresponding methods.
*/
function restoreAllServices() {
for (const service in services) {
restoreService(service);
}
}
/**
* Restores a single mocked service and its corresponding methods.
*/
function restoreService(service) {
if (services[service]) {
restoreAllMethods(service);
if (services[service].stub)
services[service].stub.restore();
delete services[service];
} else {
console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
}
}
/**
* Restores all mocked methods on a service.
*/
function restoreAllMethods(service) {
for (const method in services[service].methodMocks) {
restoreMethod(service, method);
}
}
/**
* Restores a single mocked method on a service.
*/
function restoreMethod(service, method) {
if (services[service] && services[service].methodMocks[method]) {
if (services[service].methodMocks[method].stub) {
// restore this method on all clients
services[service].clients.forEach(client => {
if (client[method] && typeof client[method].restore === 'function') {
client[method].restore();
}
})
}
delete services[service].methodMocks[method];
} else {
console.log('Method ' + service + ' was never instantiated yet you try to restore it.');
}
}
(function() {
const setPromisesDependency = _AWS.config.setPromisesDependency;
/* istanbul ignore next */
/* only to support for older versions of aws-sdk */
if (typeof setPromisesDependency === 'function') {
AWS.Promise = global.Promise;
_AWS.config.setPromisesDependency = function(p) {
AWS.Promise = p;
return setPromisesDependency(p);
};
}
})();
module.exports = AWS;
<MSG> Update index.js
<DFF> @@ -98,8 +98,10 @@ function mockServiceMethod(service, client, method, replace) {
}
}
}
-
- return (function invokeMock() {
+
+ return invokeMock()
+
+ function invokeMock() {
// If the value of 'replace' is a function we call it with the arguments.
if(typeof(replace) === 'function') {
return replace.apply(replace, args);
@@ -109,7 +111,7 @@ function mockServiceMethod(service, client, method, replace) {
var callback = args[args.length - 1];
return callback(null, replace);
}
- })()
+ }
});
}
| 5 | Update index.js | 3 | .js | js | apache-2.0 | dwyl/aws-sdk-mock |
670 | <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();
}));
});
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();
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> Fix to use 'Buffer.alloc' instead of 'new Buffer'
https://nodejs.org/en/docs/guides/buffer-constructor-deprecation/
<DFF> @@ -254,7 +254,7 @@ 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', new Buffer('body'));
+ awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
var s3 = new AWS.S3();
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
| 1 | Fix to use 'Buffer.alloc' instead of 'new Buffer' | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
671 | <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();
}));
});
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();
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> Fix to use 'Buffer.alloc' instead of 'new Buffer'
https://nodejs.org/en/docs/guides/buffer-constructor-deprecation/
<DFF> @@ -254,7 +254,7 @@ 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', new Buffer('body'));
+ awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body'));
var s3 = new AWS.S3();
var req = s3.getObject('getObject', {});
var stream = req.createReadStream();
| 1 | Fix to use 'Buffer.alloc' instead of 'new Buffer' | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
672 | <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) {
st.end();
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
});
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 #34 from dwyl/restoring_should_not_throw_errors
Restoring will not throw errors anymore
<DFF> @@ -283,6 +283,18 @@ test('AWS.mock function should mock AWS service and method on the service', func
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 {
+ var stub = awsMock.mock('CloudSearchDomain', 'search');
+ awsMock.restore('SES', 'sendEmail');
+ awsMock.restore('CloudSearchDomain', 'doesnotexist');
+ st.end();
+ } catch (e) {
+ console.log(e)
+ }
+
+ });
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
| 12 | Merge pull request #34 from dwyl/restoring_should_not_throw_errors | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
673 | <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) {
st.end();
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
});
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 #34 from dwyl/restoring_should_not_throw_errors
Restoring will not throw errors anymore
<DFF> @@ -283,6 +283,18 @@ test('AWS.mock function should mock AWS service and method on the service', func
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 {
+ var stub = awsMock.mock('CloudSearchDomain', 'search');
+ awsMock.restore('SES', 'sendEmail');
+ awsMock.restore('CloudSearchDomain', 'doesnotexist');
+ st.end();
+ } catch (e) {
+ console.log(e)
+ }
+
+ });
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
| 12 | Merge pull request #34 from dwyl/restoring_should_not_throw_errors | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
674 | <NME> workflow.yml
<BEF> ADDFILE
<MSG> Merge pull request #240 from abetomo/add_github_actions_yml
ci: add .github/workflows/workflow.yml
<DFF> @@ -0,0 +1,18 @@
+name: Node CI
+
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ node-version: [12.x, 14.x, 16.x]
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions/setup-node@v2
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: npm i
+ - run: npm test
| 18 | Merge pull request #240 from abetomo/add_github_actions_yml | 0 | .yml | github/workflows/workflow | apache-2.0 | dwyl/aws-sdk-mock |
675 | <NME> workflow.yml
<BEF> ADDFILE
<MSG> Merge pull request #240 from abetomo/add_github_actions_yml
ci: add .github/workflows/workflow.yml
<DFF> @@ -0,0 +1,18 @@
+name: Node CI
+
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ node-version: [12.x, 14.x, 16.x]
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions/setup-node@v2
+ with:
+ node-version: ${{ matrix.node-version }}
+ - run: npm i
+ - run: npm test
| 18 | Merge pull request #240 from abetomo/add_github_actions_yml | 0 | .yml | github/workflows/workflow | apache-2.0 | dwyl/aws-sdk-mock |
676 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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 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> Merge pull request #249 from emptyshell/main
Update README.md with sinon.js official page link
<DFF> @@ -34,7 +34,7 @@ Using stubs means you can prevent a specific method from being called directly.
## What?
-Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods.
+Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods.
## *How*? (*Usage*)
| 1 | Merge pull request #249 from emptyshell/main | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
677 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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 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> Merge pull request #249 from emptyshell/main
Update README.md with sinon.js official page link
<DFF> @@ -34,7 +34,7 @@ Using stubs means you can prevent a specific method from being called directly.
## What?
-Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods.
+Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods.
## *How*? (*Usage*)
| 1 | Merge pull request #249 from emptyshell/main | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
678 | <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(() => {
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.end();
});
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> Allow passing in a sinon stub or jest mock as the replacement function and automatically wrap it as a fully functional replacement fn
<DFF> @@ -7,6 +7,8 @@ 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;
@@ -583,6 +585,76 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
});
+ t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
+ const sinonStub = sinon.stub();
+ sinonStub.returns('message');
+ awsMock.mock('DynamoDB', 'getItem', sinonStub);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(data, 'message');
+ st.equal(sinonStub.called, true);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
+ const sinonStub = sinon.stub();
+ sinonStub.returns('message');
+ awsMock.mock('DynamoDB', 'getItem', sinonStub);
+ const db = new AWS.DynamoDB();
+ db.getItem({}).promise().then(function(data){
+ st.equal(data, 'message');
+ st.equal(sinonStub.called, true);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
+ const jestMock = jest.fn().mockReturnValue('message');
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(data, 'message');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
+ const jestMock = jest.fn().mockResolvedValue('message');
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(data, 'message');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
+ const jestMock = jest.fn().mockImplementation(() => {
+ throw new Error('something went wrong')
+ });
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err){
+ st.equal(err.message, 'something went wrong');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
+ const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err){
+ st.equal(err.message, 'something went wrong');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
t.end();
});
| 72 | Allow passing in a sinon stub or jest mock as the replacement function and automatically wrap it as a fully functional replacement fn | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
679 | <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(() => {
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.end();
});
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> Allow passing in a sinon stub or jest mock as the replacement function and automatically wrap it as a fully functional replacement fn
<DFF> @@ -7,6 +7,8 @@ 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;
@@ -583,6 +585,76 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
});
+ t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
+ const sinonStub = sinon.stub();
+ sinonStub.returns('message');
+ awsMock.mock('DynamoDB', 'getItem', sinonStub);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(data, 'message');
+ st.equal(sinonStub.called, true);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
+ const sinonStub = sinon.stub();
+ sinonStub.returns('message');
+ awsMock.mock('DynamoDB', 'getItem', sinonStub);
+ const db = new AWS.DynamoDB();
+ db.getItem({}).promise().then(function(data){
+ st.equal(data, 'message');
+ st.equal(sinonStub.called, true);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
+ const jestMock = jest.fn().mockReturnValue('message');
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(data, 'message');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
+ const jestMock = jest.fn().mockResolvedValue('message');
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err, data){
+ st.equal(data, 'message');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
+ const jestMock = jest.fn().mockImplementation(() => {
+ throw new Error('something went wrong')
+ });
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err){
+ st.equal(err.message, 'something went wrong');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
+ t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
+ const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
+ awsMock.mock('DynamoDB', 'getItem', jestMock);
+ const db = new AWS.DynamoDB();
+ db.getItem({}, function(err){
+ st.equal(err.message, 'something went wrong');
+ st.equal(jestMock.mock.calls.length, 1);
+ st.end();
+ });
+ });
+
t.end();
});
| 72 | Allow passing in a sinon stub or jest mock as the replacement function and automatically wrap it as a fully functional replacement fn | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
680 | <NME> index.test.js
<BEF> var test = require('tape');
var awsMock = require('../index.js');
var AWS = require('aws-sdk');
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('mock function replaces method with a function that returns replace string', function(st){
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){
st.end();
});
})
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
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) {
});
})
}
t.test('all the methods on a service are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
});
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 #40 from motiz88/request-read-stream
Add minimal createReadStream support
<DFF> @@ -1,6 +1,8 @@
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');
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){
@@ -103,6 +105,26 @@ 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);
+ });
+ 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(){
+ return lambda.createFunction({}).promise()
+ }).catch(function(data){
+ st.equals(data, error);
+ st.end();
+ });
+ })
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
@@ -126,6 +148,22 @@ 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) {});
+ 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', {});
+ var stream = req.createReadStream();
+ stream.pipe(concatStream(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");
| 38 | Merge pull request #40 from motiz88/request-read-stream | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
681 | <NME> index.test.js
<BEF> var test = require('tape');
var awsMock = require('../index.js');
var AWS = require('aws-sdk');
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('mock function replaces method with a function that returns replace string', function(st){
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){
st.end();
});
})
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
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) {
});
})
}
t.test('all the methods on a service are restored', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, "message");
});
});
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 #40 from motiz88/request-read-stream
Add minimal createReadStream support
<DFF> @@ -1,6 +1,8 @@
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');
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){
@@ -103,6 +105,26 @@ 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);
+ });
+ 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(){
+ return lambda.createFunction({}).promise()
+ }).catch(function(data){
+ st.equals(data, error);
+ st.end();
+ });
+ })
t.test('promises can be configured', function(st){
awsMock.restore('Lambda', 'getFunction');
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
@@ -126,6 +148,22 @@ 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) {});
+ 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', {});
+ var stream = req.createReadStream();
+ stream.pipe(concatStream(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");
| 38 | Merge pull request #40 from motiz88/request-read-stream | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
682 | <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.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);
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> Remove `var` as it is the second assignment
<DFF> @@ -378,7 +378,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);
| 1 | Remove `var` as it is the second assignment | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
683 | <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.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);
const sns1 = new AWS.SNS();
const sns2 = new AWS.SNS();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(sns1.publish.isSinonProxy, true);
st.equal(sns2.publish.isSinonProxy, true);
awsMock.restore('SNS');
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('all the services are restored when no arguments given to awsMock.restore', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
awsMock.mock('DynamoDB', 'putItem', function(params, callback){
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){
callback(null, 'test');
});
const sns = new AWS.SNS();
const docClient = new AWS.DynamoDB.DocumentClient();
const dynamoDb = new AWS.DynamoDB();
st.equal(AWS.SNS.isSinonProxy, true);
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(sns.publish.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(dynamoDb.putItem.isSinonProxy, true);
awsMock.restore();
st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('a nested service can be mocked properly', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'put', 'message');
const docClient = new AWS.DynamoDB.DocumentClient();
awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) {
callback(null, 'test');
});
awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
callback(null, 'test');
});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.put.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
docClient.put({}, function(err, data){
st.equal(data, 'message');
docClient.get({}, function(err, data){
st.equal(data, 'test');
awsMock.restore('DynamoDB.DocumentClient', 'get');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
awsMock.restore('DynamoDB.DocumentClient');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false);
st.end();
});
});
});
t.test('a nested service can be mocked properly even when paramValidation is set', function(st){
awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) {
callback(null, 'test');
});
const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true});
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(docClient.query.isSinonProxy, true);
docClient.query({}, function(err, data){
st.equal(err, null);
st.equal(data, 'test');
st.end();
});
});
t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) {
awsMock.mock('DynamoDB.DocumentClient', 'get', 'message');
awsMock.mock('DynamoDB', 'getItem', 'test');
const docClient = new AWS.DynamoDB.DocumentClient();
let dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
awsMock.mock('DynamoDB', 'getItem', 'test');
dynamoDb = new AWS.DynamoDB();
st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.isSinonProxy, true);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB.DocumentClient');
// the first assertion is true because DynamoDB is still mocked
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true);
st.equal(AWS.DynamoDB.isSinonProxy, true);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.isSinonProxy, true);
awsMock.restore('DynamoDB');
st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false);
st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false);
st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false);
st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false);
st.end();
});
t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) {
awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
return callback(null, 'message');
});
const csd = new AWS.CloudSearchDomain({
endpoint: 'some endpoint',
region: 'eu-west'
});
awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) {
return callback(null, 'message');
});
csd.search({}, function(err, data) {
st.equal(data, 'message');
});
csd.suggest({}, function(err, data) {
st.equal(data, 'message');
});
st.end();
});
t.skip('Mocked service should return the sinon stub', function(st) {
// TODO: the stub is only returned if an instance was already constructed
const stub = awsMock.mock('CloudSearchDomain', 'search');
st.equal(stub.stub.isSinonProxy, true);
st.end();
});
t.test('Restore should not fail when the stub did not exist.', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('Lambda');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Restore should not fail when service was not mocked', function (st) {
// This test will fail when restoring throws unneeded errors.
try {
awsMock.restore('CloudFormation');
awsMock.restore('UnknownService');
st.end();
} catch (e) {
console.log(e);
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
const req = s3.getObject({Bucket: 'b', notKey: 'k'});
st.equal(req.on('httpHeaders', ()=>{}), req);
st.end();
});
t.test('Mocked service should return replaced function when request send is called', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
let returnedValue = '';
const s3 = new AWS.S3();
const req = s3.getObject('getObject', {});
req.send(async (err, data) => {
returnedValue = data.Body;
});
st.equal(returnedValue, 'body');
st.end();
});
t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) {
const sinonStub = sinon.stub();
sinonStub.returns('message');
awsMock.mock('DynamoDB', 'getItem', sinonStub);
const db = new AWS.DynamoDB();
db.getItem({}).promise().then(function(data){
st.equal(data, 'message');
st.equal(sinonStub.called, true);
st.end();
});
});
t.test('mock function replaces method with a jest mock and returns successfully', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn().mockReturnValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and resolves successfully', function(st) {
const jestMock = jest.fn().mockResolvedValue('message');
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(data, 'message');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and fails successfully', function(st) {
const jestMock = jest.fn(() => {
throw new Error('something went wrong')
});
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock and rejects successfully', function(st) {
const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err){
st.equal(err.message, 'something went wrong');
st.equal(jestMock.mock.calls.length, 1);
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem({}, function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) {
const jestMock = jest.fn((params, cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) {
const jestMock = jest.fn((cb) => cb(null, 'item'));
awsMock.mock('DynamoDB', 'getItem', jestMock);
const db = new AWS.DynamoDB();
db.getItem(function(err, data){
st.equal(jestMock.mock.calls.length, 1);
st.equal(data, 'item');
st.end();
});
});
t.end();
});
test('AWS.setSDK function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('Modules with multi-parameter constructors can be set for mocking', function(st) {
awsMock.setSDK('aws-sdk');
awsMock.mock('CloudFront.Signer', 'getSignedUrl');
const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key');
st.type(signer, 'Signer');
st.end();
});
t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) {
awsMock.setSDK('sinon');
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDK('aws-sdk');
st.end();
});
t.end();
});
test('AWS.setSDKInstance function should mock a specific AWS module', function(t) {
t.test('Specific Modules can be set for mocking', function(st) {
const aws2 = require('aws-sdk');
awsMock.setSDKInstance(aws2);
awsMock.mock('SNS', 'publish', 'message2');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message2');
st.end();
});
});
t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) {
const bad = {};
awsMock.setSDKInstance(bad);
st.throws(function() {
awsMock.mock('SNS', 'publish', 'message');
});
awsMock.setSDKInstance(AWS);
st.end();
});
t.end();
});
<MSG> Remove `var` as it is the second assignment
<DFF> @@ -378,7 +378,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);
| 1 | Remove `var` as it is the second assignment | 1 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
684 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
const test = tap.test;
const awsMock = require('../index.js');
const AWS = require('aws-sdk');
const isNodeStream = require('is-node-stream');
const concatStream = require('concat-stream');
const Readable = require('stream').Readable;
const jest = require('jest-mock');
const sinon = require('sinon');
AWS.config.paramValidation = false;
tap.afterEach(() => {
awsMock.restore();
});
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('mock function replaces method with a function that returns replace string', function(st){
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
callback(null, options);
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equal(data.test, 'message');
st.end();
});
});
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
st.end();
});
});
t.test('method with no input rules can be mocked even if paramValidation is set', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
t.test('method succeeds on valid input when paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equal(data.Body, 'body');
st.end();
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'test');
st.end();
});
});
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
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 #153 from mankins/feature/remockable
allow remocking with new values
<DFF> @@ -98,6 +98,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
});
});
+ t.test('service is re-mocked when remock called', function(st){
+ awsMock.mock('SNS', 'subscribe', function(params, callback){
+ callback(null, 'message 1');
+ });
+ var sns = new AWS.SNS();
+ awsMock.remock('SNS', 'subscribe', function(params, callback){
+ callback(null, 'message 2');
+ });
+ sns.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');
| 13 | Merge pull request #153 from mankins/feature/remockable | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
685 | <NME> index.test.js
<BEF> 'use strict';
const tap = require('tap');
const test = tap.test;
const awsMock = require('../index.js');
const AWS = require('aws-sdk');
const isNodeStream = require('is-node-stream');
const concatStream = require('concat-stream');
const Readable = require('stream').Readable;
const jest = require('jest-mock');
const sinon = require('sinon');
AWS.config.paramValidation = false;
tap.afterEach(() => {
awsMock.restore();
});
test('AWS.mock function should mock AWS service and method on the service', function(t){
t.test('mock function replaces method with a function that returns replace string', function(st){
awsMock.mock('SNS', 'publish', 'message');
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('mock function replaces method with replace function', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('method which accepts any number of arguments can be mocked', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3();
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
awsMock.mock('S3', 'upload', function(params, options, callback) {
callback(null, options);
});
s3.upload({}, {test: 'message'}, function(err, data) {
st.equal(data.test, 'message');
st.end();
});
});
});
t.test('method fails on invalid input if paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) {
st.ok(err);
st.notOk(data);
st.end();
});
});
t.test('method with no input rules can be mocked even if paramValidation is set', function(st) {
awsMock.mock('S3', 'getSignedUrl', 'message');
const s3 = new AWS.S3({paramValidation: true});
s3.getSignedUrl('getObject', {}, function(err, data) {
st.equal(data, 'message');
st.end();
});
});
t.test('method succeeds on valid input when paramValidation is set', function(st) {
awsMock.mock('S3', 'getObject', {Body: 'body'});
const s3 = new AWS.S3({paramValidation: true});
s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) {
st.notOk(err);
st.equal(data.Body, 'body');
st.end();
});
});
t.test('method is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'test');
});
sns.publish({}, function(err, data){
st.equal(data, 'message');
st.end();
});
});
t.test('service is not re-mocked if a mock already exists', function(st){
awsMock.mock('SNS', 'publish', function(params, callback){
callback(null, 'message');
});
const sns = new AWS.SNS();
awsMock.mock('SNS', 'subscribe', function(params, callback){
callback(null, 'test');
st.end();
});
});
t.test('multiple methods can be mocked on the same service', function(st){
awsMock.mock('Lambda', 'getFunction', function(params, callback) {
callback(null, 'message');
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 #153 from mankins/feature/remockable
allow remocking with new values
<DFF> @@ -98,6 +98,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
});
});
+ t.test('service is re-mocked when remock called', function(st){
+ awsMock.mock('SNS', 'subscribe', function(params, callback){
+ callback(null, 'message 1');
+ });
+ var sns = new AWS.SNS();
+ awsMock.remock('SNS', 'subscribe', function(params, callback){
+ callback(null, 'message 2');
+ });
+ sns.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');
| 13 | Merge pull request #153 from mankins/feature/remockable | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
686 | <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();
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
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> added test scenario to support new functionality
<DFF> @@ -245,6 +245,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('request object createReadStream works with returned streams', function(st) {
+ awsMock.mock('S3', 'getObject', () => {
+ const bodyStream = new Readable();
+ bodyStream.push('body');
+ bodyStream.push(null);
+ return bodyStream;
+ });
+ const stream = new AWS.S3().getObject('getObject').createReadStream();
+ stream.pipe(concatStream(function(actual) {
+ st.equals(actual.toString(), 'body');
+ st.end();
+ }));
+ });
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
| 13 | added test scenario to support new functionality | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
687 | <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();
st.end();
}));
});
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
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> added test scenario to support new functionality
<DFF> @@ -245,6 +245,19 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.end();
}));
});
+ t.test('request object createReadStream works with returned streams', function(st) {
+ awsMock.mock('S3', 'getObject', () => {
+ const bodyStream = new Readable();
+ bodyStream.push('body');
+ bodyStream.push(null);
+ return bodyStream;
+ });
+ const stream = new AWS.S3().getObject('getObject').createReadStream();
+ stream.pipe(concatStream(function(actual) {
+ st.equals(actual.toString(), 'body');
+ st.end();
+ }));
+ });
t.test('request object createReadStream works with strings', function(st) {
awsMock.mock('S3', 'getObject', 'body');
const s3 = new AWS.S3();
| 13 | added test scenario to support new functionality | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
688 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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> 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 | Update README.md | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
689 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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> 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 | Update README.md | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
690 | <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');
});
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', '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.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('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();
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
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 #218 from ellenaua/master
When remock is called, update all instances of client
<DFF> @@ -112,6 +112,26 @@ 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');
@@ -336,6 +356,44 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(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.equals(AWS.SNS.isSinonProxy, true);
+ st.equals(sns1.publish.isSinonProxy, true);
+ st.equals(sns2.publish.isSinonProxy, true);
+
+ awsMock.restore('SNS', 'publish');
+
+ st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
+ st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
+ st.equals(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.equals(AWS.SNS.isSinonProxy, true);
+ st.equals(sns1.publish.isSinonProxy, true);
+ st.equals(sns2.publish.isSinonProxy, true);
+
+ awsMock.restore('SNS');
+
+ st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
+ st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
+ st.equals(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');
@@ -494,6 +552,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
}
});
+ 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();
| 69 | Merge pull request #218 from ellenaua/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
691 | <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');
});
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', '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.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('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();
}
});
t.test('Mocked service should allow chained calls after listening to events', function (st) {
awsMock.mock('S3', 'getObject');
const s3 = new AWS.S3();
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 #218 from ellenaua/master
When remock is called, update all instances of client
<DFF> @@ -112,6 +112,26 @@ 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');
@@ -336,6 +356,44 @@ test('AWS.mock function should mock AWS service and method on the service', func
st.equals(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.equals(AWS.SNS.isSinonProxy, true);
+ st.equals(sns1.publish.isSinonProxy, true);
+ st.equals(sns2.publish.isSinonProxy, true);
+
+ awsMock.restore('SNS', 'publish');
+
+ st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true);
+ st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
+ st.equals(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.equals(AWS.SNS.isSinonProxy, true);
+ st.equals(sns1.publish.isSinonProxy, true);
+ st.equals(sns2.publish.isSinonProxy, true);
+
+ awsMock.restore('SNS');
+
+ st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false);
+ st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false);
+ st.equals(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');
@@ -494,6 +552,17 @@ test('AWS.mock function should mock AWS service and method on the service', func
}
});
+ 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();
| 69 | Merge pull request #218 from ellenaua/master | 0 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
692 | <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> Replace 'var' with 'const' or 'let'
'const' or 'let' is better.
<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 | Replace 'var' with 'const' or 'let' | 63 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
693 | <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> Replace 'var' with 'const' or 'let'
'const' or 'let' is better.
<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 | Replace 'var' with 'const' or 'let' | 63 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
694 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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> 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 | Update README.md | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
695 | <NME> README.md
<BEF> # aws-sdk-mock
AWSome mocks for Javascript aws-sdk services.
[](https://travis-ci.org/dwyl/aws-sdk-mock)
[](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master)
[](https://david-dm.org/dwyl/aws-sdk-mock)
[](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies)
[](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
[](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> 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 | Update README.md | 1 | .md | md | apache-2.0 | dwyl/aws-sdk-mock |
696 | <NME> index.d.ts
<BEF> declare module 'aws-sdk-mock' {
function mock(service: string, method: string, replace: any): void;
function mock(
service: string,
method: string,
replace: (params: any, callback: (err: any, data: any) => void) => void
): 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, method?: string): void;
function setSDK(path: string): void;
}
export type Callback<D> = (err: AWSError | undefined, data: D) => void;
export type ReplaceFn<C extends ClientName, M extends MethodName<C>> = (params: AWSRequest<C, M>, callback: AWSCallback<C, M>) => void
export function mock<C extends ClientName, M extends MethodName<C>>(
service: C,
method: M,
replace: ReplaceFn<C, M>,
): void;
export function mock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void;
export function mock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void;
export function remock<C extends ClientName, M extends MethodName<C>>(
service: C,
method: M,
replace: ReplaceFn<C, M>,
): void;
export function remock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void;
export function remock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void;
export function restore<C extends ClientName>(service?: C, method?: MethodName<C>): void;
export function restore<C extends ClientName, NC extends NestedClientName<C>>(service?: NestedClientFullName<C, NC>, method?: NestedMethodName<C, NC>): void;
export function setSDK(path: string): void;
export function setSDKInstance(instance: typeof import('aws-sdk')): void;
/**
* The SDK defines a class for each service as well as a namespace with the same name.
* Nested clients, e.g. DynamoDB.DocumentClient, are defined on the namespace, not the class.
* That is why we need to fetch these separately as defined below in the NestedClientName<C> type
*
* The NestedClientFullName type supports validating strings representing a nested clients name in dot notation
*
* We add the ts-ignore comments to avoid the type system to trip over the many possible values for NestedClientName<C>
*/
export type NestedClientName<C extends ClientName> = keyof typeof AWS[C];
// @ts-ignore
export type NestedClientFullName<C extends ClientName, NC extends NestedClientName<C>> = `${C}.${NC}`;
// @ts-ignore
export type NestedClient<C extends ClientName, NC extends NestedClientName<C>> = InstanceType<(typeof AWS)[C][NC]>;
// @ts-ignore
export type NestedMethodName<C extends ClientName, NC extends NestedClientName<C>> = keyof ExtractMethod<NestedClient<C, NC>>;
<MSG> Merge pull request #242 from captain-yossarian/issue/241
Fix function overload order
<DFF> @@ -1,19 +1,20 @@
declare module 'aws-sdk-mock' {
- function mock(service: string, method: string, replace: any): void;
-
function mock(
service: string,
method: string,
replace: (params: any, callback: (err: any, data: any) => void) => void
): void;
- function remock(service: string, method: string, replace: any): void;
+ function mock(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 remock(service: string, method: string, replace: any): void;
+
function restore(service?: string, method?: string): void;
function setSDK(path: string): void;
| 4 | Merge pull request #242 from captain-yossarian/issue/241 | 3 | .ts | d | apache-2.0 | dwyl/aws-sdk-mock |
697 | <NME> index.d.ts
<BEF> declare module 'aws-sdk-mock' {
function mock(service: string, method: string, replace: any): void;
function mock(
service: string,
method: string,
replace: (params: any, callback: (err: any, data: any) => void) => void
): 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, method?: string): void;
function setSDK(path: string): void;
}
export type Callback<D> = (err: AWSError | undefined, data: D) => void;
export type ReplaceFn<C extends ClientName, M extends MethodName<C>> = (params: AWSRequest<C, M>, callback: AWSCallback<C, M>) => void
export function mock<C extends ClientName, M extends MethodName<C>>(
service: C,
method: M,
replace: ReplaceFn<C, M>,
): void;
export function mock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void;
export function mock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void;
export function remock<C extends ClientName, M extends MethodName<C>>(
service: C,
method: M,
replace: ReplaceFn<C, M>,
): void;
export function remock<C extends ClientName>(service: C, method: MethodName<C>, replace: any): void;
export function remock<C extends ClientName, NC extends NestedClientName<C>>(service: NestedClientFullName<C, NC>, method: NestedMethodName<C, NC>, replace: any): void;
export function restore<C extends ClientName>(service?: C, method?: MethodName<C>): void;
export function restore<C extends ClientName, NC extends NestedClientName<C>>(service?: NestedClientFullName<C, NC>, method?: NestedMethodName<C, NC>): void;
export function setSDK(path: string): void;
export function setSDKInstance(instance: typeof import('aws-sdk')): void;
/**
* The SDK defines a class for each service as well as a namespace with the same name.
* Nested clients, e.g. DynamoDB.DocumentClient, are defined on the namespace, not the class.
* That is why we need to fetch these separately as defined below in the NestedClientName<C> type
*
* The NestedClientFullName type supports validating strings representing a nested clients name in dot notation
*
* We add the ts-ignore comments to avoid the type system to trip over the many possible values for NestedClientName<C>
*/
export type NestedClientName<C extends ClientName> = keyof typeof AWS[C];
// @ts-ignore
export type NestedClientFullName<C extends ClientName, NC extends NestedClientName<C>> = `${C}.${NC}`;
// @ts-ignore
export type NestedClient<C extends ClientName, NC extends NestedClientName<C>> = InstanceType<(typeof AWS)[C][NC]>;
// @ts-ignore
export type NestedMethodName<C extends ClientName, NC extends NestedClientName<C>> = keyof ExtractMethod<NestedClient<C, NC>>;
<MSG> Merge pull request #242 from captain-yossarian/issue/241
Fix function overload order
<DFF> @@ -1,19 +1,20 @@
declare module 'aws-sdk-mock' {
- function mock(service: string, method: string, replace: any): void;
-
function mock(
service: string,
method: string,
replace: (params: any, callback: (err: any, data: any) => void) => void
): void;
- function remock(service: string, method: string, replace: any): void;
+ function mock(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 remock(service: string, method: string, replace: any): void;
+
function restore(service?: string, method?: string): void;
function setSDK(path: string): void;
| 4 | Merge pull request #242 from captain-yossarian/issue/241 | 3 | .ts | d | apache-2.0 | dwyl/aws-sdk-mock |
698 | <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();
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.
var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
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> Added debug so at least you get a message when you have it enabled
<DFF> @@ -285,10 +285,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
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.
- var stub = awsMock.mock('CloudSearchDomain', 'search');
- awsMock.restore('SES', 'sendEmail');
- awsMock.restore('CloudSearchDomain', 'doesnotexist');
- st.end();
+ try {
+ var stub = awsMock.mock('CloudSearchDomain', 'search');
+ awsMock.restore('SES', 'sendEmail');
+ awsMock.restore('CloudSearchDomain', 'doesnotexist');
+ st.end();
+ } catch (e) {
+ console.log(e)
+ }
+
});
});
| 9 | Added debug so at least you get a message when you have it enabled | 4 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
699 | <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();
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.
var stub = awsMock.mock('CloudSearchDomain', 'search');
awsMock.restore('SES', 'sendEmail');
awsMock.restore('CloudSearchDomain', 'doesnotexist');
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> Added debug so at least you get a message when you have it enabled
<DFF> @@ -285,10 +285,15 @@ test('AWS.mock function should mock AWS service and method on the service', func
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.
- var stub = awsMock.mock('CloudSearchDomain', 'search');
- awsMock.restore('SES', 'sendEmail');
- awsMock.restore('CloudSearchDomain', 'doesnotexist');
- st.end();
+ try {
+ var stub = awsMock.mock('CloudSearchDomain', 'search');
+ awsMock.restore('SES', 'sendEmail');
+ awsMock.restore('CloudSearchDomain', 'doesnotexist');
+ st.end();
+ } catch (e) {
+ console.log(e)
+ }
+
});
});
| 9 | Added debug so at least you get a message when you have it enabled | 4 | .js | test | apache-2.0 | dwyl/aws-sdk-mock |
Subsets and Splits