Hapi error logging

Peter BanjoPeter Banjo
1 min read

It was so annoying - there I was trying to test my hapi server but it was broken and I had no idea why. Because I was using server.inject the errors where not being shown in the console. How do I log the error messages from a stub server?

suite('getBlogFiles', () => {
    let server;

    beforeEach(() => {
        server = Hapi.Server();
        const preResponse = function(request, h) {
            const { response } = request;
            if (!response.isBoom) {
                return h.continue;
            }

            return console.warn(response);
        };

        server.ext('onPreResponse', preResponse);
    });

    test('get posts route gets markdown files', async () => {
        const files = ['that.md', 'this.md'];
        const getBlogFiles = sinon.stub().resolves(files);
        const stubMethods = [{ name: 'blog.getBlogFiles', method: getBlogFiles }];

        await server.register({
            plugin,
            options: { methods: stubMethods },
        });

        const { method, url } = routes.v1.get_blog_posts();
        // errors disappearing between here...
        const { result } = await server.inject({
            method,
            url,
        });
        // ... and here

        expect(result).to.equal(files);
    });
});

So I got on the Hapi hour slack channel to ask this question and a in a few minutes Eran told me

@iampeterbanjo it's coming soon, but for now just throw server.events.on('request', console.log) to see what's up.

Brilliant! It feels great to be using a framework from such a friendly and helpful community.

0
Subscribe to my newsletter

Read articles from Peter Banjo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Peter Banjo
Peter Banjo

I build meaningful software by empathising with design, development and business needs. My interests are test automation, functional programming and full-stack web development using NodeJS and other tools.