I'm writing a web app using nodejs
. I have some utils functions which I export and test separately. There is another function though, that calls some of those utils functions that I would like to stub (using sinon
).
From what I've seen so far, I can only stub methods on objects, so how should I design my utilities functions so I can test all of them?
function util1() {
...
}
function util2() {
...
}
function util3() {
...
util1();
...
util2();
}
export {
util1,
util2,
util3
}
Inside util3
I want to mock (or stub) the calls for util1
and util2
.
You could put util1 and util2 in a separate module and then use some solution or existing module like mock-require
https://github.com/boblauer/mock-require .
But perhaps the simplest solution is actually to change your design to use objects. Then you could create your object with stubs and feed it into an object with a util3 method.
One easy way would be to:
function util3() {
...
moddule.exports.util1();
...
module.exports.util2();
}
The second way is to wrap everything in a map
var self = module.exports = {
util3 : function() {
self.util2();
},
util2 : function() { },
..}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.