Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to mock hapi.js reply with sinon for unit testing

Is there simple way of mocking the hapi reply object/function for easy unit testing?

The examples I see for hapi all use server.inject and the "lab" framwork for testing. I'm curious to see how I could keep using mocha and would like to test controller directly rather than injecting into the server.

Should i use sinon to mock the reply object?

test/post.js

  before(function () { 
    PostController = proxyquire('../controllers/post', { 'mongoose': mongooseMock });
  });


  it('should be able to create a post', function(done){

    var request.payload = {foo:bar};
    var reply = sinon.spy(); //is this how I should mock this?
    PostController.create.handler(request, reply);
    reply.should ...// how do I test for statuscode 201, Boom errors, and response msgs

  });

controllers/post.js

var Boom = require('Boom')
    Post = require('../models/Post')
module.exports = {

  create: {
    auth: 'token',
    handler: function (request, reply) {

    var p = new Post({foo:request.payload.foo});
    p.save(function (err, results) {
        if (!err && results)
            reply(results).created();
        else {
            reply(Boom.badImplementation(err));
        }
      });

    }
}

Finally, should I just switch over to lab instead?

like image 209
MonkeyBonkey Avatar asked Jan 03 '15 15:01

MonkeyBonkey


1 Answers

You can use server.inject() with Mocha too. I would just stub Post.save():

Sinon.stub(Post, 'save', function (callback) {

    callback(null, { foo: 'bar' });
});

With some more code:

it('creates a post', function (done) {

    Sinon.stub(Post, 'save', function (callback) {

        callback(null, { foo: 'bar' });
    });

    server.inject({ method: 'POST', url: '/posts', payload: { foo: 'bar' } }, function (res) {

        Post.save.restore();    

        expect(res.statusCode).to.equal(201);
        done();
    });
});

If you want to test for the error, you just need to modify the stub:

it('returns an error when save fails', function (done) {

    Sinon.stub(Post, 'save', function (callback) {

        callback(new Error('test'), null);
    });

    server.inject({ method: 'POST', url: '/posts', payload: { foo: 'bar' } }, function (res) {

        Post.save.restore();    

        expect(res.statusCode).to.equal(500);
        done();
    });
});
like image 190
Gergo Erdosi Avatar answered Sep 22 '22 03:09

Gergo Erdosi