简体   繁体   中英

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?

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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM