Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  95] [ 5]  / answers: 1 / hits: 21079  / 10 Years ago, tue, june 17, 2014, 12:00:00

Edit: Being a little bit more precise.



I want to test usecases for a Github API wrapper extension, that our team has created. For testing, we don't want to use API wrapper extension directly, so we want to stub out its functions. All calls to the API wrapper should be stubbed out for the tests, not just creating a clone stub.



I have a module github in Node.js:



module.exports = function(args, done) {
...
}


And I am requiring it like this:



var github = require('../services/github');


Now, I would like to stub out github(...) using Sinon.js:



var stub_github = sinon.stub(???, github, function (args, callback) { 
console.log(the github(...) call was stubbed out!!);
});


But sinon.stub(...) expects from me to pass an object and a method and does not allow me to stub out a module that is a function.



Any ideas?


More From » node.js

 Answers
7

There might be a way to accomplish this in pure Sinon, but I suspect it would be pretty hacky. However, proxyquire is a node library that is designed for solving these sort of issues.



Supposing you want to test some module foo that makes use of the github module; you'd write something like:



var proxyquire = require(proxyquire);
var foo = proxyquire(.foo, {./github, myFakeGithubStub});


where myFakeGithubStub can be anything; a complete stub, or the actual implementation with a few tweaks, etc.



If, in the above example, myFakeGithubStub has a property @global set as true, (i.e. by executing myFakeGithubStub[@global] = true) then the github module will be replaced with the stub not only in the foo module itself, but in any module that the foo module requires. However, as stated in the proxyquire documentation on the global option, generally speaking this feature is a sign of poorly designed unit tests and should be avoided.


[#70532] Sunday, June 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;