我试图在AWS Firehose对象上模拟putRecord方法,但是模拟没有成功。代码最终调用firehose对象上的aws-sdk api,该对象与实时aws服务对话。下面的代码中有什么错误?要避免这种实时服务调用并使mock有效,需要进行哪些更改?
有没有办法发送thenable对象,而不是像下面的回调那样只发送普通对象?也就是说,以某种方式使用我在测试代码中定义的callbackFunc?
另外,最终我需要检查mock是否被调用。我该如何做到这一点?我可以以某种方式使用sinon.stub来实现这一点吗?这样以后我就可以进行验证了。多么?
以下是代码和测试代码部分...修改为此帖子的简单形式。
作为文件一部分的代码,比如samplelogging.js。..。
/*jshint strict:true */
/*jshint node:true */
/*jshint esversion:6 */
/*jshint mocha:true */
"use strict";
var Promise = require('bluebird');
var AWS = require('aws-sdk');
var uuid = require('uuid');
AWS.config.setPromisesDependency(Promise);
var Logger = {
/**
* Get's a AWS Firehose Instance
*/
getFirehoseInstance: function getFirehoseInstance() {
if (!(this.firehose)) {
this.firehose = new AWS.Firehose({apiVersion: "2015-08-04", region: "us-west-2"});
}
return this.firehose;
},
getLogger: function getLogger(options) {
options = options || {};
let self = this;
self.class = options.class;
self.firehose = self.getFirehoseInstance();
return self;
},
logInfo: function logInfo(dataToLog, callback) {
this._log("info", dataToLog)
.then(function (data){
if (callback) {
callback();
}
});
return;
},
/**
* @api: private
*/
_log: function _log(traceLevel, dataToLog) {
return new Promise(function(resolve, reject) {
var params = params || {};
AWS.config.update({ logger: process.stdout });
AWS.config.update({ retries: 3 });
var recordParams = {
type: params.type || 'LogEntry'
};
if (typeof dataToLog === 'string' || dataToLog instanceof String) {
recordParams.data = { message: dataToLog };
} else {
recordParams.data = dataToLog;
}
recordParams.data.id = uuid.v1();
recordParams.data.preciseTimestamp = Math.floor(new Date().getTime()/1000);
recordParams.data.class = this.class;
recordParams.data.traceLevel = traceLevel;
var firehoseRecordParams = {
DeliveryStreamName: "mystreamname", //replace mystreamname with real stream name
Record: {
Data: JSON.stringify(recordParams)+',\n'
}
};
this.firehose.putRecord(firehoseRecordParams, function(err, recordId) {
console.log("debug: recordId returned by putRecord = " + JSON.stringify(recordId));
return resolve(recordId);
});
}.bind(this));
}
};
module.exports = Logger;下面是我的测试代码,它是一个文件的一部分,比如sampleloggingtest.js ...
var expect = require('chai').expect;
var Promise = require("bluebird");
var sinon = require("sinon");
var AWSMock = require('aws-sdk-mock');
describe.only("Logging tests", function () {
it.only("Test AWS firehose API invoked", function (done) {
let mylogger = Logger.getLogger({class: "Unit Test"});
let firehoseInstance = mylogger.getFirehoseInstance();
// want to have a callback function that returns a thenable object and not just an object. Not sure how to use it though with mock
// so for now this is just code that shows what i intend to do.
let callBackFunc = function( err, recordId) {
console.log("debug: returend from putRecord, recordId = " + JSON.stringify(recordId));
return Promise.resolve(recordId);
};
// calling mock as per the documentation at https://github.com/dwyl/aws-sdk-mock
AWSMock.mock('Firehose', 'putRecord', function(params, callback) {
console.log("debug: callback to putRecord to be called");
callback(null, {"RecordId": "12345"} );
});
// calling a method that should call firehose logging but our mock should intercept it - though it doesn't.
mylogger.logInfo({ prop1: "value1" }, function(){
console.log("debug: in the callback that was passed to logInfo...");
done();
});
});
});发布于 2017-05-10 02:30:38
分享我想出来的答案,特别是因为另一个人(mmorrisson)也在尝试这样做。
本质上,我将_setFirehoseInstance方法添加到我的记录器类中,这个方法只能在我的测试代码中调用,它用我自己的简单模拟类替换了firehose实例(在生产代码中应该调用新的AWS.Firehose())。
在我的测试代码中...设firehoseMock = {};
在beforeEach()中创建并设置模拟来替换实际的afterEach实例,然后在afterEach()中恢复该实例。
beforeEach(function (done) {
logger = new Logger({class: "Unit Test"});
firehose = logger.getFirehoseInstance();
consoleMock = sinon.mock(console);
firehoseMock.putRecord = function(params, callback) {
let recordIdObj = {"RecordId": recordIdVal};
callback(null, recordIdObj);
};
logger._setFirehoseInstance(firehoseMock);
sinon.spy(firehoseMock, "putRecord");
done();
});
afterEach(function (done) {
firehoseMock.putRecord.restore();
logger._setFirehoseInstance(firehose);
consoleMock.restore();
done();
});在我们尝试记录的测试代码中,检查是否调用了firehoseMock.putRecord ...
it("Test AWS firehose API invoked", function (done) {
logger.setMode("production");
logger.setEnvironment("test");
logger.logInfo({ prop1: "value1" }, function(data){
expect(firehoseMock.putRecord.calledOnce).to.equal(true); // should have been called once
expect(data.RecordId).to.equal(recordIdVal); // should have matching recordId
done();
});
});在生产代码中,在logger类中有用于firehose实例的getter和setter。
/**
* Get's a AWS Firehose Instance
*/
getFirehoseInstance() {
if (!(this.firehose)) {
this.firehose = new AWS.Firehose({apiVersion: Config.apiVersion, region: Config.region});
}
return this.firehose;
}
/**
* Set a AWS Firehose Instance - for TEST purose
*/
_setFirehoseInstance(firehoseInstance) {
if (firehoseInstance) {
this.firehose = firehoseInstance;
}
}这对我很有效。当logger在生产中调用firehose实例方法时,它将转到AWS服务,但在单元测试中,当我调用日志方法时,它会调用mock上的putRecord,因为我已经用mock替换了firehose实例。然后,我可以适当地测试是否调用了模拟上的putRecord (使用sinon.spy)。
https://stackoverflow.com/questions/43333769
复制相似问题