|
| 1 | +var events = require('events'); |
| 2 | +var sinon = require('sinon'); |
| 3 | +var _AWS = require('aws-sdk'); |
| 4 | +var traverse = require('traverse'); |
| 5 | + |
| 6 | +module.exports = _AWS; |
| 7 | +module.exports.stub = stubMethod; |
| 8 | + |
| 9 | +/** |
| 10 | + * Replaces a single AWS service method with a stub. |
| 11 | + * |
| 12 | + * @param {string} service - the name of the AWS service. Can include `.` for |
| 13 | + * nested services, e.g. `'DynamoDB.DocumentClient'`. |
| 14 | + * @param {string} method - the name of the service method to stub. |
| 15 | + * @param {function} [replacement] - if specified, this function will be called |
| 16 | + * when the service method stub is invoked. `this` in the context of the function |
| 17 | + * will provide a reference to stubbed AWS.Request and AWS.Response objects to |
| 18 | + * simulate more advanced aws-sdk-js usage patterns. |
| 19 | + * @returns {object} stub - [a sinon stub](http://sinonjs.org/docs/#stubs). |
| 20 | + */ |
| 21 | +function stubMethod(service, method, replacement) { |
| 22 | + if (!isStubbed(service)) stubService(service); |
| 23 | + if (!replacement) return sinon.stub(getService(service).prototype, method); |
| 24 | + |
| 25 | + return sinon.stub(getService(service).prototype, method, function(params, callback) { |
| 26 | + var _this = { request: stubRequest(), response: stubResponse() }; |
| 27 | + replacement.call(_this, params, callback); |
| 28 | + return _this.request; |
| 29 | + }); |
| 30 | +} |
| 31 | + |
| 32 | +function isStubbed(service) { |
| 33 | + return getService(service).isSinonProxy; |
| 34 | +} |
| 35 | + |
| 36 | +function getService(name) { |
| 37 | + return traverse(_AWS).get(name.split('.')); |
| 38 | +} |
| 39 | + |
| 40 | +function setService(name, fn) { |
| 41 | + traverse(_AWS).set(name.split('.'), fn); |
| 42 | +} |
| 43 | + |
| 44 | +function stubService(service) { |
| 45 | + var Original = getService(service); |
| 46 | + var client = new Original(); |
| 47 | + |
| 48 | + function FakeService(config) { Object.assign(this, new Original(config)); } |
| 49 | + FakeService.prototype = Object.assign({}, client.__proto__); |
| 50 | + |
| 51 | + var spy = sinon.spy(FakeService); |
| 52 | + spy.restore = function() { setService(service, Original); }; |
| 53 | + |
| 54 | + setService(service, spy); |
| 55 | +} |
| 56 | + |
| 57 | +function stubRequest() { |
| 58 | + var req = new events.EventEmitter(); |
| 59 | + var stubbed = sinon.createStubInstance(_AWS.Request); |
| 60 | + for (var method in req.__proto__) delete stubbed[method]; |
| 61 | + return Object.assign(req, stubbed); |
| 62 | +} |
| 63 | + |
| 64 | +function stubResponse() { |
| 65 | + var req = new events.EventEmitter(); |
| 66 | + var stubbed = sinon.createStubInstance(_AWS.Response); |
| 67 | + for (var method in req.__proto__) delete stubbed[method]; |
| 68 | + return Object.assign(req, stubbed); |
| 69 | +} |
0 commit comments