Request to Add functionality to Allow Running of overloaded method unless alternate return set

49 views
Skip to first unread message

Robert Wlaschin

unread,
Jul 18, 2017, 9:12:32 PM7/18/17
to Sinon.JS
Sometimes it's super useful to stub out a function for particular calls.

Take the fs.readFileSync function.  This might be used in a program to load a config file which would be useful to stub to ensure the the config file is validated properly and returns the correct responses .. etc . However, require() uses fs.readFileSync to load the JS files.  So stubbing this function outright would not be possible.

For business reasons it might not be feasible to rewrite classes/modules to expose these functions so it would be nice to provide a similar feature.


function SinonWrapper(context,property) {
// Creates a stub that by default calls the original
var stub = Sinon.stub(context,property);
stub.callsFake( function() {
// console.log(arguments)
return stub.wrappedMethod.apply(context,arguments)
})
return stub
}


// Usage ....

fs.existsSync = SinonHelper.wrap(fs,"existsSync")
fs.existsSync
.withArgs("/etc/zde.conf").returns(true)
.withArgs("./config/test0.test1.test2.json").returns(true)

fs.readFileSync = SinonHelper.wrap(fs,"readFileSync")
fs.readFileSync
.withArgs("/etc/zde.conf").returns(
// role is a value that changes what is loaded!
"{\"role\" : \"test\","
+"\"region\" : \"test\","
+"\"placement-availability-zone\" : \"test\","
+"\"instance-id\" : \"test\","
+"\"region-config\" : \"test0.test1.test2.js\"}"
)
.withArgs("./config/test0.test1.test2.json").returns(
"{ \"rtb\":{ \"activeDSPIDs\": [], \"activeSSPIDs\" : [] }, \"dsps\" : { \"testdsp\" : {} }, \"ssps\" : { \"testssp\" : {}} }"
)
.withArgs("./config/server.json").returns(
"{}"
)
.withArgs("./config/redis.test1.json").returns(
"{ \"dsp\" : { \"list\" : [], \"connections\" : [] },"
+"\"uuid\" : { \"list\" : [], \"connections\" : [] },"
+"\"cache\" : { \"list\" : [], \"connections\" : [] }, "
+"\"userSegments\" : { \"list\" : [], \"connections\" : [] } "
+"}"
)
Reply all
Reply to author
Forward
0 new messages