I am having trouble writing a unit test for the following installation as a jira.js file (in a node.js module):
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; };
Now I want to write unit test for my getIssue function. A "restler" is a REST client through which I make JIRA API REST calls to get a JIRA problem through my code.
So, in order to be able to test createIssue (..), I want to be able to make fun of the "rest" var in my Jasmine unit tests.
How can I mock this method? Please give me some pointers so that I can go forward. I tried using rewire, but I failed.
This is what still does not work for me (i.e. the getIssue method turns out to be undefined):
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); }); });
If someone can direct me on how to mock "rest" requires addiction and unit test, this method will be very useful.
Also, how do I make fun of the 'conf' passed to module.exports?
thanks