Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  198] [ 7]  / answers: 1 / hits: 21158  / 11 Years ago, sat, march 30, 2013, 12:00:00

I want to stub node.js built-ins like fs so that I don't actually make any system level file calls. The only thing I can think to do is to pass in fs and all other built-ins as an argument to all of my functions to avoid the real fs from being used. This seems a little bit silly and creates a verbose function signature crowded with built ins as arguments.





var fs = require('fs');

function findFile(path, callback) {
_findFile(fs, path, callback);
}

function _findFile(fs, path, callback) {
fs.readdir(path, function(err, files) {
//Do something.
});
}


And then during testing:



var stubFs = {
readdir: function(path, callback) {
callback(null, []);
}
};

_findFile.(stubFs, testThing, testCallback);


There's a better way than this right?


More From » node.js

 Answers
1

I like using rewire for stubbing out require(...) statements



Module Under test



module-a.js



var fs = require('fs')
function findFile(path, callback) {
fs.readdir(path, function(err, files) {
//Do something.
})
}


Test Code



module-a-test.js



var rewire = require('rewire')
var moduleA = rewire('./moduleA')
// stub out fs
var fsStub = {
readdir: function(path, callback) {
console.log('fs.readdir stub called')
callback(null, [])
}
}
moduleA.__set__('fs', fsStub)
// call moduleA which now has a fs stubbed out
moduleA()

[#79227] Thursday, March 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
simone

Total Points: 558
Total Questions: 96
Total Answers: 99

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;