我遇到了编写单元测试的问题,以下是一个jira.js文件(在一个node.js模块中)的设置:
var rest = require('restler'); // https://www.npmjs.com/package/restler
module.exports = function (conf) {
var exported = {};
exported.getIssue = function (issueId, done) {
...
rest.get(uri).on('complete', function(data, response) {
...
};
return exported;
};
现在,我想为我的getIssue函数编写单元测试。'restler'是一个REST客户端,通过它我可以通过我的代码调用JIRA API来获取JIRA问题。
因此,为了能够测试createIssue(..),我希望能够在Jasmine单元测试中模拟'rest'变量。
我应该如何模拟这个方法?请给我一些指针,以便我可以继续前进。我尝试过使用rewire但失败了。
这是我到目前为止的内容,它不起作用(即getIssue方法变成未定义):
var rewire = require("rewire");
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var cfg = require("../../../config.js").Configuration;
var jiraModule = rewire("../lib/jira")(cfg);
var sinon = require("sinon");
var should = require("should");
// https://github.com/danwrong/restler
var restMock = {
init : function () {
console.log('mock initiated'+JSON.stringify(this));
},
postJson : function (url, data, options) {
console.log('[restler] POST url='+url+', data= '+JSON.stringify(data)+
'options='+JSON.stringify(options));
emitter.once('name_of_event',function(data){
console.log('EVent received!'+data);
});
emitter.emit('name_of_event', "test");
emitter.emit('name_of_event');
emitter.emit('name_of_event');
},
get : function (url, options) {
console.log('[restler] GET url='+url+'options='+JSON.stringify(options));
},
del : function (url, options) {
console.log('[restler] DELETE url='+url+'options='+JSON.stringify(options));
},
putJson : function (url, data, options) {
console.log('[restler] PUT url='+url+', data= '+JSON.stringify(data)+
'options='+JSON.stringify(options));
}
};
var cfgMock = {
"test" : "testing"
};
jiraModule.__set__("rest", restMock);
jiraModule.__set__("cfg", cfgMock);
console.log('mod='+JSON.stringify(jiraModule.__get__("rest")));
describe("A suite", function() {
it("contains spec with an expectation", function() {
restMock.init();
restMock.postJson(null, null, null);
console.log(cfg.jira);
// the following method turns out to be undefined but when i console.log out the jiraModule, i see the entire code outputted from that file
jiraModule.getIssue("SRMAPP-130", function (err, result) {
console.log('data= '+JSON.stringify(result));
});
expect(true).toBe(true);
});
});
如果有人能指导我如何模拟'rest' require依赖项并对这种方法进行单元测试,那将非常有帮助。
另外,我应该如何模拟传递给module.exports的'conf'?
谢谢。
rest.postJson().on()
可以理解为rest.postJson()
返回一个具有on
方法的对象{on: function(){}}
,随后调用该on
方法。如果您查看存根,它也是这样做的。您也可以使用EventEmitter
。 - Sarbbottam