How to taunt with hapi.js answer with sinon for unit testing

Is there an easy way to mock a hapi response object / function for simple device testing?

In the examples I see for hapi, everyone uses server.inject and the "laboratory" framework for testing. I am curious to see how I can continue to use mocha and would like to test the controller directly, and not enter it on the server.

Should I use sinon to grind the response 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 to work in the lab?

+6
source share
1 answer

You can use server.inject() with Mocha. I will just close Post.save() :

 Sinon.stub(Post, 'save', function (callback) { callback(null, { foo: 'bar' }); }); 

With one 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 the error, you just need to change 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(); }); }); 
+3
source

Source: https://habr.com/ru/post/980471/


All Articles