12

I want to test hapi routes with lab, I am using mysql database.

The problem using Server.inject to test the route is that i can't mock the database because I am not calling the file that contains the handler function, so how do I inject mock database in handler?

Manan Vaghasiya
  • 881
  • 1
  • 10
  • 25

1 Answers1

5

You should be able to use something like sinon to mock anything you require. For example, let's say you have a dbHandler.js somewhere:

var db = require('db');

module.exports.handleOne = function(request, reply) {
    reply(db.findOne());
}

And then in your server.js:

var Hapi = require('hapi'),
    dbHandler = require('dbHandler')

var server = new Hapi.Server(); server.connection({ port: 3000 });

server.route({
    method: 'GET',
    path: '/',
    handler: dbHandler.handleOne
});

You can still mock out that call, because all calls to require are cached. So, in your test.js:

var sinon = require('sinon'),
    server = require('server'),
    db = require('db');

sinon.stub(db, 'findOne').returns({ one: 'fakeOne' });
// now the real findOne won't be called until you call db.findOne.restore()
server.inject({ url: '/' }, function (res) {
    expect(res.one).to.equal('fakeOne');
});
SlightlyCuban
  • 3,185
  • 1
  • 20
  • 31
  • What do you mean by 'cached "require"'? – Manan Vaghasiya Mar 03 '15 at 14:22
  • 2
    @MananVaghasiya see http://nodejs.org/api/globals.html#globals_require_cache . Once resolved, `require` will cache the object, and subsequent calls to `require` for a module will return the cached instance of said module. – SlightlyCuban Mar 03 '15 at 14:48