After the suggestion from @AlbertZaccagni above, I consulted the documentation from Sinon, and I came up with the following:
NB: I omit code that declares routes and other integral parts of the question.
Assuming userDb.js is a module that connects to the database, and that I want to mock the answer from the database:
userDb.js is as follows:
var db = require(); module.exports.getUser = function(id, callback){ db.query('sql query', function(err, rows){ if(err){ return callback(err); } return callback(null, rows[0]); }); }
In my test folder, I created the mytest.js file with the following contents:
//don't forget to install sinon JS via npm var sinon = require('sinon'); var server = require(/*path to hapi server*/); var userDb = require(/*path to the module we are stubbing/mocking*/); describe('Stub test', function(){ var options = {}; options.method = 'GET'; options.url = '/user/1'; it('with stubbing', function(done) { var stub = sinon.stub(userDb, 'getUser', function(id, callback) { if (id < 5) { return callback(null, 100);/*in this case i'm just testing to see if this function will get called instead- of the actual function. That why 100.*/ } return new Error('test error'); }); server.inject(options, function(res) { var result = res.result; res.statusCode.should.equal(200); result.num.should.equal(100); done(); }); }); });
When I run the npm test in my working directory, I see that it passes without actually calling the database and returns 100 for username 1.
source share