Search code examples
node.jsnode-mysqlsequelize.jshapi.js

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?


Solution

  • 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');
    });