How to check exceptions in the lab?

I am writing test cases using lab , and I would like to check if an exception is thrown from my plugin. The problem is that hapi allows you to eliminate the bubble while setting the answer to the internal server 500 error, which is why my test fails.

We can check this answer expect(res.statusCode).to.equal(500) , but the test will still fail.

I cannot use try / catch around server.inject because an exception is thrown asynchronously.

How to use a laboratory to check for exceptions?

+5
source share
1 answer

An error that occurs inside the handler breaks the domain of the request object. You can check for this pair of different ways.

I am not very happy with either of these ideas, but they both work. Hope someone else knows a better way.

Plugin

 exports.register = function (server, options, next) { server.route({ method: 'GET', path: '/', handler: function (request, reply) { throw new Error('You should test for this'); reply(); } }); next(); } 

Test

 describe('Getting the homepage', function () { it('Throws an error', function (done) { server.inject({url: '/'}, function (resp) { var error = resp.request.response._error; expect(error).to.be.an.instanceof(Error); expect(error.message).to.equal('Uncaught error: You should test for this'); done(); }); }); }); 

Alternative

If you do not like the idea of ​​accessing the _error private property (as described above), you can add a listener to the domain and save the error yourself in the object request.

 server.ext('onPreHandler', function (request, reply) { request.domain.on('error', function (error) { request.caughtError = error; }); reply.continue(); }); 

Test

 describe('Getting the homepage', function () { it('Throws an error', function (done) { server.inject({url: '/'}, function (resp) { var error = resp.request.caughtError; expect(error).to.be.an.instanceof(Error); expect(error.message).to.equal('Uncaught error: You should test for this'); done(); }); }); }); 
+2
source

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


All Articles