Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to inject mock testing hapi with Server.inject

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?

like image 366
Manan Vaghasiya Avatar asked Aug 14 '14 14:08

Manan Vaghasiya


1 Answers

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');
});
like image 106
SlightlyCuban Avatar answered Oct 04 '22 20:10

SlightlyCuban